aboutsummaryrefslogtreecommitdiffstats
path: root/gcc-4.9/gcc/config/avr/avr.c
blob: fa979df4660ffeb0c2692216a5f3120dea5ca765 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
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
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
/* Subroutines for insn-output.c for ATMEL AVR micro controllers
   Copyright (C) 1998-2014 Free Software Foundation, Inc.
   Contributed by Denis Chertykov (chertykov@gmail.com)

   This file is part of GCC.

   GCC is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.
   
   GCC is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with GCC; see the file COPYING3.  If not see
   <http://www.gnu.org/licenses/>.  */

#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "rtl.h"
#include "regs.h"
#include "hard-reg-set.h"
#include "insn-config.h"
#include "conditions.h"
#include "insn-attr.h"
#include "insn-codes.h"
#include "flags.h"
#include "reload.h"
#include "tree.h"
#include "print-tree.h"
#include "calls.h"
#include "stor-layout.h"
#include "stringpool.h"
#include "output.h"
#include "expr.h"
#include "c-family/c-common.h"
#include "diagnostic-core.h"
#include "obstack.h"
#include "function.h"
#include "recog.h"
#include "optabs.h"
#include "ggc.h"
#include "langhooks.h"
#include "tm_p.h"
#include "target.h"
#include "target-def.h"
#include "params.h"
#include "df.h"

/* Maximal allowed offset for an address in the LD command */
#define MAX_LD_OFFSET(MODE) (64 - (signed)GET_MODE_SIZE (MODE))

/* Return true if STR starts with PREFIX and false, otherwise.  */
#define STR_PREFIX_P(STR,PREFIX) (0 == strncmp (STR, PREFIX, strlen (PREFIX)))

/* The 4 bits starting at SECTION_MACH_DEP are reserved to store the
   address space where data is to be located.
   As the only non-generic address spaces are all located in flash,
   this can be used to test if data shall go into some .progmem* section.
   This must be the rightmost field of machine dependent section flags.  */
#define AVR_SECTION_PROGMEM (0xf * SECTION_MACH_DEP)

/* Similar 4-bit region for SYMBOL_REF_FLAGS.  */
#define AVR_SYMBOL_FLAG_PROGMEM (0xf * SYMBOL_FLAG_MACH_DEP)

/* Similar 4-bit region in SYMBOL_REF_FLAGS:
   Set address-space AS in SYMBOL_REF_FLAGS of SYM  */
#define AVR_SYMBOL_SET_ADDR_SPACE(SYM,AS)                       \
  do {                                                          \
    SYMBOL_REF_FLAGS (sym) &= ~AVR_SYMBOL_FLAG_PROGMEM;         \
    SYMBOL_REF_FLAGS (sym) |= (AS) * SYMBOL_FLAG_MACH_DEP;      \
  } while (0)

/* Read address-space from SYMBOL_REF_FLAGS of SYM  */
#define AVR_SYMBOL_GET_ADDR_SPACE(SYM)                          \
  ((SYMBOL_REF_FLAGS (sym) & AVR_SYMBOL_FLAG_PROGMEM)           \
   / SYMBOL_FLAG_MACH_DEP)

/* Known address spaces.  The order must be the same as in the respective
   enum from avr.h (or designated initialized must be used).  */
const avr_addrspace_t avr_addrspace[ADDR_SPACE_COUNT] =
{
  { ADDR_SPACE_RAM,  0, 2, "", 0, NULL },
  { ADDR_SPACE_FLASH,  1, 2, "__flash",   0, ".progmem.data" },
  { ADDR_SPACE_FLASH1, 1, 2, "__flash1",  1, ".progmem1.data" },
  { ADDR_SPACE_FLASH2, 1, 2, "__flash2",  2, ".progmem2.data" },
  { ADDR_SPACE_FLASH3, 1, 2, "__flash3",  3, ".progmem3.data" },
  { ADDR_SPACE_FLASH4, 1, 2, "__flash4",  4, ".progmem4.data" },
  { ADDR_SPACE_FLASH5, 1, 2, "__flash5",  5, ".progmem5.data" },
  { ADDR_SPACE_MEMX, 1, 3, "__memx",  0, ".progmemx.data" },
};


/* Holding RAM addresses of some SFRs used by the compiler and that
   are unique over all devices in an architecture like 'avr4'.  */

typedef struct
{
  /* SREG: The processor status */
  int sreg;

  /* RAMPX, RAMPY, RAMPD and CCP of XMEGA */
  int ccp;
  int rampd;
  int rampx;
  int rampy;

  /* RAMPZ: The high byte of 24-bit address used with ELPM */
  int rampz;

  /* SP: The stack pointer and its low and high byte */
  int sp_l;
  int sp_h;
} avr_addr_t;

static avr_addr_t avr_addr;


/* Prototypes for local helper functions.  */

static const char* out_movqi_r_mr (rtx, rtx[], int*);
static const char* out_movhi_r_mr (rtx, rtx[], int*);
static const char* out_movsi_r_mr (rtx, rtx[], int*);
static const char* out_movqi_mr_r (rtx, rtx[], int*);
static const char* out_movhi_mr_r (rtx, rtx[], int*);
static const char* out_movsi_mr_r (rtx, rtx[], int*);

static int get_sequence_length (rtx insns);
static int sequent_regs_live (void);
static const char *ptrreg_to_str (int);
static const char *cond_string (enum rtx_code);
static int avr_num_arg_regs (enum machine_mode, const_tree);
static int avr_operand_rtx_cost (rtx, enum machine_mode, enum rtx_code,
                                 int, bool);
static void output_reload_in_const (rtx*, rtx, int*, bool);
static struct machine_function * avr_init_machine_status (void);


/* Prototypes for hook implementors if needed before their implementation.  */

static bool avr_rtx_costs (rtx, int, int, int, int*, bool);


/* Allocate registers from r25 to r8 for parameters for function calls.  */
#define FIRST_CUM_REG 26

/* Implicit target register of LPM instruction (R0) */
extern GTY(()) rtx lpm_reg_rtx;
rtx lpm_reg_rtx;

/* (Implicit) address register of LPM instruction (R31:R30 = Z) */
extern GTY(()) rtx lpm_addr_reg_rtx;
rtx lpm_addr_reg_rtx;

/* Temporary register RTX (reg:QI TMP_REGNO) */
extern GTY(()) rtx tmp_reg_rtx;
rtx tmp_reg_rtx;

/* Zeroed register RTX (reg:QI ZERO_REGNO) */
extern GTY(()) rtx zero_reg_rtx;
rtx zero_reg_rtx;

/* RTXs for all general purpose registers as QImode */
extern GTY(()) rtx all_regs_rtx[32];
rtx all_regs_rtx[32];

/* SREG, the processor status */
extern GTY(()) rtx sreg_rtx;
rtx sreg_rtx;

/* RAMP* special function registers */
extern GTY(()) rtx rampd_rtx;
extern GTY(()) rtx rampx_rtx;
extern GTY(()) rtx rampy_rtx;
extern GTY(()) rtx rampz_rtx;
rtx rampd_rtx;
rtx rampx_rtx;
rtx rampy_rtx;
rtx rampz_rtx;

/* RTX containing the strings "" and "e", respectively */
static GTY(()) rtx xstring_empty;
static GTY(()) rtx xstring_e;

/* Current architecture.  */
const avr_arch_t *avr_current_arch;

/* Current device.  */
const avr_mcu_t *avr_current_device;

/* Section to put switch tables in.  */
static GTY(()) section *progmem_swtable_section;

/* Unnamed sections associated to __attribute__((progmem)) aka. PROGMEM
   or to address space __flash* or __memx.  Only used as singletons inside
   avr_asm_select_section, but it must not be local there because of GTY.  */
static GTY(()) section *progmem_section[ADDR_SPACE_COUNT];

/* Condition for insns/expanders from avr-dimode.md.  */
bool avr_have_dimode = true;

/* To track if code will use .bss and/or .data.  */
bool avr_need_clear_bss_p = false;
bool avr_need_copy_data_p = false;


/* Transform UP into lowercase and write the result to LO.
   You must provide enough space for LO.  Return LO.  */

static char*
avr_tolower (char *lo, const char *up)
{
  char *lo0 = lo;

  for (; *up; up++, lo++)
    *lo = TOLOWER (*up);

  *lo = '\0';

  return lo0;
}


/* Custom function to count number of set bits.  */

static inline int
avr_popcount (unsigned int val)
{
  int pop = 0;

  while (val)
    {
      val &= val-1;
      pop++;
    }

  return pop;
}


/* Constraint helper function.  XVAL is a CONST_INT or a CONST_DOUBLE.
   Return true if the least significant N_BYTES bytes of XVAL all have a
   popcount in POP_MASK and false, otherwise.  POP_MASK represents a subset
   of integers which contains an integer N iff bit N of POP_MASK is set.  */

bool
avr_popcount_each_byte (rtx xval, int n_bytes, int pop_mask)
{
  int i;

  enum machine_mode mode = GET_MODE (xval);

  if (VOIDmode == mode)
    mode = SImode;

  for (i = 0; i < n_bytes; i++)
    {
      rtx xval8 = simplify_gen_subreg (QImode, xval, mode, i);
      unsigned int val8 = UINTVAL (xval8) & GET_MODE_MASK (QImode);

      if (0 == (pop_mask & (1 << avr_popcount (val8))))
        return false;
    }

  return true;
}


/* Access some RTX as INT_MODE.  If X is a CONST_FIXED we can get
   the bit representation of X by "casting" it to CONST_INT.  */

rtx
avr_to_int_mode (rtx x)
{
  enum machine_mode mode = GET_MODE (x);

  return VOIDmode == mode
    ? x
    : simplify_gen_subreg (int_mode_for_mode (mode), x, mode, 0);
}


/* Implement `TARGET_OPTION_OVERRIDE'.  */

static void
avr_option_override (void)
{
  flag_delete_null_pointer_checks = 0;

  /* caller-save.c looks for call-clobbered hard registers that are assigned
     to pseudos that cross calls and tries so save-restore them around calls
     in order to reduce the number of stack slots needed.

     This might lead to situations where reload is no more able to cope
     with the challenge of AVR's very few address registers and fails to
     perform the requested spills.  */

  if (avr_strict_X)
    flag_caller_saves = 0;

  /* Unwind tables currently require a frame pointer for correctness,
     see toplev.c:process_options().  */

  if ((flag_unwind_tables
       || flag_non_call_exceptions
       || flag_asynchronous_unwind_tables)
      && !ACCUMULATE_OUTGOING_ARGS)
    {
      flag_omit_frame_pointer = 0;
    }

  if (flag_pic == 1)
    warning (OPT_fpic, "-fpic is not supported");
  if (flag_pic == 2)
    warning (OPT_fPIC, "-fPIC is not supported");
  if (flag_pie == 1)
    warning (OPT_fpie, "-fpie is not supported");
  if (flag_pie == 2)
    warning (OPT_fPIE, "-fPIE is not supported");

  avr_current_device = &avr_mcu_types[avr_mcu_index];
  avr_current_arch = &avr_arch_types[avr_current_device->arch];

  /* RAM addresses of some SFRs common to all devices in respective arch. */

  /* SREG: Status Register containing flags like I (global IRQ) */
  avr_addr.sreg = 0x3F + avr_current_arch->sfr_offset;

  /* RAMPZ: Address' high part when loading via ELPM */
  avr_addr.rampz = 0x3B + avr_current_arch->sfr_offset;

  avr_addr.rampy = 0x3A + avr_current_arch->sfr_offset;
  avr_addr.rampx = 0x39 + avr_current_arch->sfr_offset;
  avr_addr.rampd = 0x38 + avr_current_arch->sfr_offset;
  avr_addr.ccp = 0x34 + avr_current_arch->sfr_offset;

  /* SP: Stack Pointer (SP_H:SP_L) */
  avr_addr.sp_l = 0x3D + avr_current_arch->sfr_offset;
  avr_addr.sp_h = avr_addr.sp_l + 1;

  init_machine_status = avr_init_machine_status;

  avr_log_set_avr_log();
}

/* Function to set up the backend function structure.  */

static struct machine_function *
avr_init_machine_status (void)
{
  return ggc_alloc_cleared_machine_function ();
}


/* Implement `INIT_EXPANDERS'.  */
/* The function works like a singleton.  */

void
avr_init_expanders (void)
{
  int regno;

  for (regno = 0; regno < 32; regno ++)
    all_regs_rtx[regno] = gen_rtx_REG (QImode, regno);

  lpm_reg_rtx  = all_regs_rtx[LPM_REGNO];
  tmp_reg_rtx  = all_regs_rtx[TMP_REGNO];
  zero_reg_rtx = all_regs_rtx[ZERO_REGNO];

  lpm_addr_reg_rtx = gen_rtx_REG (HImode, REG_Z);

  sreg_rtx = gen_rtx_MEM (QImode, GEN_INT (avr_addr.sreg));
  rampd_rtx = gen_rtx_MEM (QImode, GEN_INT (avr_addr.rampd));
  rampx_rtx = gen_rtx_MEM (QImode, GEN_INT (avr_addr.rampx));
  rampy_rtx = gen_rtx_MEM (QImode, GEN_INT (avr_addr.rampy));
  rampz_rtx = gen_rtx_MEM (QImode, GEN_INT (avr_addr.rampz));

  xstring_empty = gen_rtx_CONST_STRING (VOIDmode, "");
  xstring_e = gen_rtx_CONST_STRING (VOIDmode, "e");
}


/* Implement `REGNO_REG_CLASS'.  */
/* Return register class for register R.  */

enum reg_class
avr_regno_reg_class (int r)
{
  static const enum reg_class reg_class_tab[] =
    {
      R0_REG,
      /* r1 - r15 */
      NO_LD_REGS, NO_LD_REGS, NO_LD_REGS,
      NO_LD_REGS, NO_LD_REGS, NO_LD_REGS, NO_LD_REGS,
      NO_LD_REGS, NO_LD_REGS, NO_LD_REGS, NO_LD_REGS,
      NO_LD_REGS, NO_LD_REGS, NO_LD_REGS, NO_LD_REGS,
      /* r16 - r23 */
      SIMPLE_LD_REGS, SIMPLE_LD_REGS, SIMPLE_LD_REGS, SIMPLE_LD_REGS,
      SIMPLE_LD_REGS, SIMPLE_LD_REGS, SIMPLE_LD_REGS, SIMPLE_LD_REGS,
      /* r24, r25 */
      ADDW_REGS, ADDW_REGS,
      /* X: r26, 27 */
      POINTER_X_REGS, POINTER_X_REGS,
      /* Y: r28, r29 */
      POINTER_Y_REGS, POINTER_Y_REGS,
      /* Z: r30, r31 */
      POINTER_Z_REGS, POINTER_Z_REGS,
      /* SP: SPL, SPH */
      STACK_REG, STACK_REG
    };

  if (r <= 33)
    return reg_class_tab[r];

  return ALL_REGS;
}


/* Implement `TARGET_SCALAR_MODE_SUPPORTED_P'.  */

static bool
avr_scalar_mode_supported_p (enum machine_mode mode)
{
  if (ALL_FIXED_POINT_MODE_P (mode))
    return true;

  if (PSImode == mode)
    return true;

  return default_scalar_mode_supported_p (mode);
}


/* Return TRUE if DECL is a VAR_DECL located in flash and FALSE, otherwise.  */

static bool
avr_decl_flash_p (tree decl)
{
  if (TREE_CODE (decl) != VAR_DECL
      || TREE_TYPE (decl) == error_mark_node)
    {
      return false;
    }

  return !ADDR_SPACE_GENERIC_P (TYPE_ADDR_SPACE (TREE_TYPE (decl)));
}


/* Return TRUE if DECL is a VAR_DECL located in the 24-bit flash
   address space and FALSE, otherwise.  */

static bool
avr_decl_memx_p (tree decl)
{
  if (TREE_CODE (decl) != VAR_DECL
      || TREE_TYPE (decl) == error_mark_node)
    {
      return false;
    }

  return (ADDR_SPACE_MEMX == TYPE_ADDR_SPACE (TREE_TYPE (decl)));
}


/* Return TRUE if X is a MEM rtx located in flash and FALSE, otherwise.  */

bool
avr_mem_flash_p (rtx x)
{
  return (MEM_P (x)
          && !ADDR_SPACE_GENERIC_P (MEM_ADDR_SPACE (x)));
}


/* Return TRUE if X is a MEM rtx located in the 24-bit flash
   address space and FALSE, otherwise.  */

bool
avr_mem_memx_p (rtx x)
{
  return (MEM_P (x)
          && ADDR_SPACE_MEMX == MEM_ADDR_SPACE (x));
}


/* A helper for the subsequent function attribute used to dig for
   attribute 'name' in a FUNCTION_DECL or FUNCTION_TYPE */

static inline int
avr_lookup_function_attribute1 (const_tree func, const char *name)
{
  if (FUNCTION_DECL == TREE_CODE (func))
    {
      if (NULL_TREE != lookup_attribute (name, DECL_ATTRIBUTES (func)))
        {
          return true;
        }

      func = TREE_TYPE (func);
    }

  gcc_assert (TREE_CODE (func) == FUNCTION_TYPE
              || TREE_CODE (func) == METHOD_TYPE);

  return NULL_TREE != lookup_attribute (name, TYPE_ATTRIBUTES (func));
}

/* Return nonzero if FUNC is a naked function.  */

static int
avr_naked_function_p (tree func)
{
  return avr_lookup_function_attribute1 (func, "naked");
}

/* Return nonzero if FUNC is an interrupt function as specified
   by the "interrupt" attribute.  */

static int
avr_interrupt_function_p (tree func)
{
  return avr_lookup_function_attribute1 (func, "interrupt");
}

/* Return nonzero if FUNC is a signal function as specified
   by the "signal" attribute.  */

static int
avr_signal_function_p (tree func)
{
  return avr_lookup_function_attribute1 (func, "signal");
}

/* Return nonzero if FUNC is an OS_task function.  */

static int
avr_OS_task_function_p (tree func)
{
  return avr_lookup_function_attribute1 (func, "OS_task");
}

/* Return nonzero if FUNC is an OS_main function.  */

static int
avr_OS_main_function_p (tree func)
{
  return avr_lookup_function_attribute1 (func, "OS_main");
}


/* Implement `TARGET_SET_CURRENT_FUNCTION'.  */
/* Sanity cheching for above function attributes.  */

static void
avr_set_current_function (tree decl)
{
  location_t loc;
  const char *isr;

  if (decl == NULL_TREE
      || current_function_decl == NULL_TREE
      || current_function_decl == error_mark_node
      || ! cfun->machine
      || cfun->machine->attributes_checked_p)
    return;

  loc = DECL_SOURCE_LOCATION (decl);

  cfun->machine->is_naked = avr_naked_function_p (decl);
  cfun->machine->is_signal = avr_signal_function_p (decl);
  cfun->machine->is_interrupt = avr_interrupt_function_p (decl);
  cfun->machine->is_OS_task = avr_OS_task_function_p (decl);
  cfun->machine->is_OS_main = avr_OS_main_function_p (decl);

  isr = cfun->machine->is_interrupt ? "interrupt" : "signal";

  /* Too much attributes make no sense as they request conflicting features. */

  if (cfun->machine->is_OS_task + cfun->machine->is_OS_main
      + (cfun->machine->is_signal || cfun->machine->is_interrupt) > 1)
    error_at (loc, "function attributes %qs, %qs and %qs are mutually"
               " exclusive", "OS_task", "OS_main", isr);

  /* 'naked' will hide effects of 'OS_task' and 'OS_main'.  */

  if (cfun->machine->is_naked
      && (cfun->machine->is_OS_task || cfun->machine->is_OS_main))
    warning_at (loc, OPT_Wattributes, "function attributes %qs and %qs have"
                " no effect on %qs function", "OS_task", "OS_main", "naked");

  if (cfun->machine->is_interrupt || cfun->machine->is_signal)
    {
      tree args = TYPE_ARG_TYPES (TREE_TYPE (decl));
      tree ret = TREE_TYPE (TREE_TYPE (decl));
      const char *name;

      name = DECL_ASSEMBLER_NAME_SET_P (decl)
        ? IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl))
        : IDENTIFIER_POINTER (DECL_NAME (decl));

      /* Skip a leading '*' that might still prefix the assembler name,
         e.g. in non-LTO runs.  */

      name = default_strip_name_encoding (name);

      /* Silently ignore 'signal' if 'interrupt' is present.  AVR-LibC startet
         using this when it switched from SIGNAL and INTERRUPT to ISR.  */

      if (cfun->machine->is_interrupt)
        cfun->machine->is_signal = 0;

      /* Interrupt handlers must be  void __vector (void)  functions.  */

      if (args && TREE_CODE (TREE_VALUE (args)) != VOID_TYPE)
        error_at (loc, "%qs function cannot have arguments", isr);

      if (TREE_CODE (ret) != VOID_TYPE)
        error_at (loc, "%qs function cannot return a value", isr);

      /* If the function has the 'signal' or 'interrupt' attribute, ensure
         that the name of the function is "__vector_NN" so as to catch
         when the user misspells the vector name.  */

      if (!STR_PREFIX_P (name, "__vector"))
        warning_at (loc, 0, "%qs appears to be a misspelled %s handler",
                    name, isr);
    }

  /* Don't print the above diagnostics more than once.  */

  cfun->machine->attributes_checked_p = 1;
}


/* Implement `ACCUMULATE_OUTGOING_ARGS'.  */

int
avr_accumulate_outgoing_args (void)
{
  if (!cfun)
    return TARGET_ACCUMULATE_OUTGOING_ARGS;

  /* FIXME: For setjmp and in avr_builtin_setjmp_frame_value we don't know
        what offset is correct.  In some cases it is relative to
        virtual_outgoing_args_rtx and in others it is relative to
        virtual_stack_vars_rtx.  For example code see
            gcc.c-torture/execute/built-in-setjmp.c
            gcc.c-torture/execute/builtins/sprintf-chk.c   */

  return (TARGET_ACCUMULATE_OUTGOING_ARGS
          && !(cfun->calls_setjmp
               || cfun->has_nonlocal_label));
}


/* Report contribution of accumulated outgoing arguments to stack size.  */

static inline int
avr_outgoing_args_size (void)
{
  return ACCUMULATE_OUTGOING_ARGS ? crtl->outgoing_args_size : 0;
}


/* Implement `STARTING_FRAME_OFFSET'.  */
/* This is the offset from the frame pointer register to the first stack slot
   that contains a variable living in the frame.  */

int
avr_starting_frame_offset (void)
{
  return 1 + avr_outgoing_args_size ();
}


/* Return the number of hard registers to push/pop in the prologue/epilogue
   of the current function, and optionally store these registers in SET.  */

static int
avr_regs_to_save (HARD_REG_SET *set)
{
  int reg, count;
  int int_or_sig_p = cfun->machine->is_interrupt || cfun->machine->is_signal;

  if (set)
    CLEAR_HARD_REG_SET (*set);
  count = 0;

  /* No need to save any registers if the function never returns or
     has the "OS_task" or "OS_main" attribute.  */

  if (TREE_THIS_VOLATILE (current_function_decl)
      || cfun->machine->is_OS_task
      || cfun->machine->is_OS_main)
    return 0;

  for (reg = 0; reg < 32; reg++)
    {
      /* Do not push/pop __tmp_reg__, __zero_reg__, as well as
         any global register variables.  */

      if (fixed_regs[reg])
        continue;

      if ((int_or_sig_p && !crtl->is_leaf && call_used_regs[reg])
          || (df_regs_ever_live_p (reg)
              && (int_or_sig_p || !call_used_regs[reg])
              /* Don't record frame pointer registers here.  They are treated
                 indivitually in prologue.  */
              && !(frame_pointer_needed
                   && (reg == REG_Y || reg == (REG_Y+1)))))
        {
          if (set)
            SET_HARD_REG_BIT (*set, reg);
          count++;
        }
    }
  return count;
}


/* Implement `TARGET_ALLOCATE_STACK_SLOTS_FOR_ARGS' */

static bool
avr_allocate_stack_slots_for_args (void)
{
  return !cfun->machine->is_naked;
}


/* Return true if register FROM can be eliminated via register TO.  */

static bool
avr_can_eliminate (const int from, const int to)
{
  return ((frame_pointer_needed && to == FRAME_POINTER_REGNUM)
          || !frame_pointer_needed);
}


/* Implement `TARGET_WARN_FUNC_RETURN'.  */

static bool
avr_warn_func_return (tree decl)
{
  /* Naked functions are implemented entirely in assembly, including the
     return sequence, so suppress warnings about this.  */

  return !avr_naked_function_p (decl);
}

/* Compute offset between arg_pointer and frame_pointer.  */

int
avr_initial_elimination_offset (int from, int to)
{
  if (from == FRAME_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
    return 0;
  else
    {
      int offset = frame_pointer_needed ? 2 : 0;
      int avr_pc_size = AVR_HAVE_EIJMP_EICALL ? 3 : 2;

      offset += avr_regs_to_save (NULL);
      return (get_frame_size () + avr_outgoing_args_size()
              + avr_pc_size + 1 + offset);
    }
}


/* Helper for the function below.  */

static void
avr_adjust_type_node (tree *node, enum machine_mode mode, int sat_p)
{
  *node = make_node (FIXED_POINT_TYPE);
  TYPE_SATURATING (*node) = sat_p;
  TYPE_UNSIGNED (*node) = UNSIGNED_FIXED_POINT_MODE_P (mode);
  TYPE_IBIT (*node) = GET_MODE_IBIT (mode);
  TYPE_FBIT (*node) = GET_MODE_FBIT (mode);
  TYPE_PRECISION (*node) = GET_MODE_BITSIZE (mode);
  TYPE_ALIGN (*node) = 8;
  SET_TYPE_MODE (*node, mode);

  layout_type (*node);
}


/* Implement `TARGET_BUILD_BUILTIN_VA_LIST'.  */

static tree
avr_build_builtin_va_list (void)
{
  /* avr-modes.def adjusts [U]TA to be 64-bit modes with 48 fractional bits.
     This is more appropriate for the 8-bit machine AVR than 128-bit modes.
     The ADJUST_IBIT/FBIT are handled in toplev:init_adjust_machine_modes()
     which is auto-generated by genmodes, but the compiler assigns [U]DAmode
     to the long long accum modes instead of the desired [U]TAmode.

     Fix this now, right after node setup in tree.c:build_common_tree_nodes().
     This must run before c-cppbuiltin.c:builtin_define_fixed_point_constants()
     which built-in defines macros like __ULLACCUM_FBIT__ that are used by
     libgcc to detect IBIT and FBIT.  */

  avr_adjust_type_node (&ta_type_node, TAmode, 0);
  avr_adjust_type_node (&uta_type_node, UTAmode, 0);
  avr_adjust_type_node (&sat_ta_type_node, TAmode, 1);
  avr_adjust_type_node (&sat_uta_type_node, UTAmode, 1);

  unsigned_long_long_accum_type_node = uta_type_node;
  long_long_accum_type_node = ta_type_node;
  sat_unsigned_long_long_accum_type_node = sat_uta_type_node;
  sat_long_long_accum_type_node = sat_ta_type_node;

  /* Dispatch to the default handler.  */

  return std_build_builtin_va_list ();
}


/* Implement `TARGET_BUILTIN_SETJMP_FRAME_VALUE'.  */
/* Actual start of frame is virtual_stack_vars_rtx this is offset from
   frame pointer by +STARTING_FRAME_OFFSET.
   Using saved frame = virtual_stack_vars_rtx - STARTING_FRAME_OFFSET
   avoids creating add/sub of offset in nonlocal goto and setjmp.  */

static rtx
avr_builtin_setjmp_frame_value (void)
{
  rtx xval = gen_reg_rtx (Pmode);
  emit_insn (gen_subhi3 (xval, virtual_stack_vars_rtx,
                         gen_int_mode (STARTING_FRAME_OFFSET, Pmode)));
  return xval;
}


/* Return contents of MEM at frame pointer + stack size + 1 (+2 if 3-byte PC).
   This is return address of function.  */

rtx
avr_return_addr_rtx (int count, rtx tem)
{
  rtx r;

  /* Can only return this function's return address. Others not supported.  */
  if (count)
     return NULL;

  if (AVR_3_BYTE_PC)
    {
      r = gen_rtx_SYMBOL_REF (Pmode, ".L__stack_usage+2");
      warning (0, "%<builtin_return_address%> contains only 2 bytes"
               " of address");
    }
  else
    r = gen_rtx_SYMBOL_REF (Pmode, ".L__stack_usage+1");

  r = gen_rtx_PLUS (Pmode, tem, r);
  r = gen_frame_mem (Pmode, memory_address (Pmode, r));
  r = gen_rtx_ROTATE (HImode, r, GEN_INT (8));
  return  r;
}

/* Return 1 if the function epilogue is just a single "ret".  */

int
avr_simple_epilogue (void)
{
  return (! frame_pointer_needed
          && get_frame_size () == 0
          && avr_outgoing_args_size() == 0
          && avr_regs_to_save (NULL) == 0
          && ! cfun->machine->is_interrupt
          && ! cfun->machine->is_signal
          && ! cfun->machine->is_naked
          && ! TREE_THIS_VOLATILE (current_function_decl));
}

/* This function checks sequence of live registers.  */

static int
sequent_regs_live (void)
{
  int reg;
  int live_seq = 0;
  int cur_seq = 0;

  for (reg = 0; reg < 18; ++reg)
    {
      if (fixed_regs[reg])
        {
          /* Don't recognize sequences that contain global register
             variables.  */

          if (live_seq != 0)
            return 0;
          else
            continue;
        }

      if (!call_used_regs[reg])
        {
          if (df_regs_ever_live_p (reg))
            {
              ++live_seq;
              ++cur_seq;
            }
          else
            cur_seq = 0;
        }
    }

  if (!frame_pointer_needed)
    {
      if (df_regs_ever_live_p (REG_Y))
        {
          ++live_seq;
          ++cur_seq;
        }
      else
        cur_seq = 0;

      if (df_regs_ever_live_p (REG_Y+1))
        {
          ++live_seq;
          ++cur_seq;
        }
      else
        cur_seq = 0;
    }
  else
    {
      cur_seq += 2;
      live_seq += 2;
    }
  return (cur_seq == live_seq) ? live_seq : 0;
}

/* Obtain the length sequence of insns.  */

int
get_sequence_length (rtx insns)
{
  rtx insn;
  int length;

  for (insn = insns, length = 0; insn; insn = NEXT_INSN (insn))
    length += get_attr_length (insn);

  return length;
}


/*  Implement `INCOMING_RETURN_ADDR_RTX'.  */

rtx
avr_incoming_return_addr_rtx (void)
{
  /* The return address is at the top of the stack.  Note that the push
     was via post-decrement, which means the actual address is off by one.  */
  return gen_frame_mem (HImode, plus_constant (Pmode, stack_pointer_rtx, 1));
}

/*  Helper for expand_prologue.  Emit a push of a byte register.  */

static void
emit_push_byte (unsigned regno, bool frame_related_p)
{
  rtx mem, reg, insn;

  mem = gen_rtx_POST_DEC (HImode, stack_pointer_rtx);
  mem = gen_frame_mem (QImode, mem);
  reg = gen_rtx_REG (QImode, regno);

  insn = emit_insn (gen_rtx_SET (VOIDmode, mem, reg));
  if (frame_related_p)
    RTX_FRAME_RELATED_P (insn) = 1;

  cfun->machine->stack_usage++;
}


/*  Helper for expand_prologue.  Emit a push of a SFR via tmp_reg.
    SFR is a MEM representing the memory location of the SFR.
    If CLR_P then clear the SFR after the push using zero_reg.  */

static void
emit_push_sfr (rtx sfr, bool frame_related_p, bool clr_p)
{
  rtx insn;

  gcc_assert (MEM_P (sfr));

  /* IN __tmp_reg__, IO(SFR) */
  insn = emit_move_insn (tmp_reg_rtx, sfr);
  if (frame_related_p)
    RTX_FRAME_RELATED_P (insn) = 1;

  /* PUSH __tmp_reg__ */
  emit_push_byte (TMP_REGNO, frame_related_p);

  if (clr_p)
    {
      /* OUT IO(SFR), __zero_reg__ */
      insn = emit_move_insn (sfr, const0_rtx);
      if (frame_related_p)
        RTX_FRAME_RELATED_P (insn) = 1;
    }
}

static void
avr_prologue_setup_frame (HOST_WIDE_INT size, HARD_REG_SET set)
{
  rtx insn;
  bool isr_p = cfun->machine->is_interrupt || cfun->machine->is_signal;
  int live_seq = sequent_regs_live ();

  HOST_WIDE_INT size_max
    = (HOST_WIDE_INT) GET_MODE_MASK (AVR_HAVE_8BIT_SP ? QImode : Pmode);

  bool minimize = (TARGET_CALL_PROLOGUES
                   && size < size_max
                   && live_seq
                   && !isr_p
                   && !cfun->machine->is_OS_task
                   && !cfun->machine->is_OS_main);

  if (minimize
      && (frame_pointer_needed
          || avr_outgoing_args_size() > 8
          || (AVR_2_BYTE_PC && live_seq > 6)
          || live_seq > 7))
    {
      rtx pattern;
      int first_reg, reg, offset;

      emit_move_insn (gen_rtx_REG (HImode, REG_X),
                      gen_int_mode (size, HImode));

      pattern = gen_call_prologue_saves (gen_int_mode (live_seq, HImode),
                                         gen_int_mode (live_seq+size, HImode));
      insn = emit_insn (pattern);
      RTX_FRAME_RELATED_P (insn) = 1;

      /* Describe the effect of the unspec_volatile call to prologue_saves.
         Note that this formulation assumes that add_reg_note pushes the
         notes to the front.  Thus we build them in the reverse order of
         how we want dwarf2out to process them.  */

      /* The function does always set frame_pointer_rtx, but whether that
         is going to be permanent in the function is frame_pointer_needed.  */

      add_reg_note (insn, REG_CFA_ADJUST_CFA,
                    gen_rtx_SET (VOIDmode, (frame_pointer_needed
                                            ? frame_pointer_rtx
                                            : stack_pointer_rtx),
                                 plus_constant (Pmode, stack_pointer_rtx,
                                                -(size + live_seq))));

      /* Note that live_seq always contains r28+r29, but the other
         registers to be saved are all below 18.  */

      first_reg = 18 - (live_seq - 2);

      for (reg = 29, offset = -live_seq + 1;
           reg >= first_reg;
           reg = (reg == 28 ? 17 : reg - 1), ++offset)
        {
          rtx m, r;

          m = gen_rtx_MEM (QImode, plus_constant (Pmode, stack_pointer_rtx,
                                                  offset));
          r = gen_rtx_REG (QImode, reg);
          add_reg_note (insn, REG_CFA_OFFSET, gen_rtx_SET (VOIDmode, m, r));
        }

      cfun->machine->stack_usage += size + live_seq;
    }
  else /* !minimize */
    {
      int reg;

      for (reg = 0; reg < 32; ++reg)
        if (TEST_HARD_REG_BIT (set, reg))
          emit_push_byte (reg, true);

      if (frame_pointer_needed
          && (!(cfun->machine->is_OS_task || cfun->machine->is_OS_main)))
        {
          /* Push frame pointer.  Always be consistent about the
             ordering of pushes -- epilogue_restores expects the
             register pair to be pushed low byte first.  */

          emit_push_byte (REG_Y, true);
          emit_push_byte (REG_Y + 1, true);
        }

      if (frame_pointer_needed
          && size == 0)
        {
          insn = emit_move_insn (frame_pointer_rtx, stack_pointer_rtx);
          RTX_FRAME_RELATED_P (insn) = 1;
        }

      if (size != 0)
        {
          /*  Creating a frame can be done by direct manipulation of the
              stack or via the frame pointer. These two methods are:
                  fp =  sp
                  fp -= size
                  sp =  fp
              or
                  sp -= size
                  fp =  sp    (*)
              the optimum method depends on function type, stack and
              frame size.  To avoid a complex logic, both methods are
              tested and shortest is selected.

              There is also the case where SIZE != 0 and no frame pointer is
              needed; this can occur if ACCUMULATE_OUTGOING_ARGS is on.
              In that case, insn (*) is not needed in that case.
              We use the X register as scratch. This is save because in X
              is call-clobbered.
                 In an interrupt routine, the case of SIZE != 0 together with
              !frame_pointer_needed can only occur if the function is not a
              leaf function and thus X has already been saved.  */

          int irq_state = -1;
          HOST_WIDE_INT size_cfa = size, neg_size;
          rtx fp_plus_insns, fp, my_fp;

          gcc_assert (frame_pointer_needed
                      || !isr_p
                      || !crtl->is_leaf);

          fp = my_fp = (frame_pointer_needed
                        ? frame_pointer_rtx
                        : gen_rtx_REG (Pmode, REG_X));

          if (AVR_HAVE_8BIT_SP)
            {
              /* The high byte (r29) does not change:
                 Prefer SUBI (1 cycle) over SBIW (2 cycles, same size).  */

              my_fp = all_regs_rtx[FRAME_POINTER_REGNUM];
            }

          /* Cut down size and avoid size = 0 so that we don't run
             into ICE like PR52488 in the remainder.  */

          if (size > size_max)
            {
              /* Don't error so that insane code from newlib still compiles
                 and does not break building newlib.  As PR51345 is implemented
                 now, there are multilib variants with -msp8.

                 If user wants sanity checks he can use -Wstack-usage=
                 or similar options.

                 For CFA we emit the original, non-saturated size so that
                 the generic machinery is aware of the real stack usage and
                 will print the above diagnostic as expected.  */

              size = size_max;
            }

          size = trunc_int_for_mode (size, GET_MODE (my_fp));
          neg_size = trunc_int_for_mode (-size, GET_MODE (my_fp));

          /************  Method 1: Adjust frame pointer  ************/

          start_sequence ();

          /* Normally, the dwarf2out frame-related-expr interpreter does
             not expect to have the CFA change once the frame pointer is
             set up.  Thus, we avoid marking the move insn below and
             instead indicate that the entire operation is complete after
             the frame pointer subtraction is done.  */

          insn = emit_move_insn (fp, stack_pointer_rtx);
          if (frame_pointer_needed)
            {
              RTX_FRAME_RELATED_P (insn) = 1;
              add_reg_note (insn, REG_CFA_ADJUST_CFA,
                            gen_rtx_SET (VOIDmode, fp, stack_pointer_rtx));
            }

          insn = emit_move_insn (my_fp, plus_constant (GET_MODE (my_fp),
                                                       my_fp, neg_size));

          if (frame_pointer_needed)
            {
              RTX_FRAME_RELATED_P (insn) = 1;
              add_reg_note (insn, REG_CFA_ADJUST_CFA,
                            gen_rtx_SET (VOIDmode, fp,
                                         plus_constant (Pmode, fp,
                                                        -size_cfa)));
            }

          /* Copy to stack pointer.  Note that since we've already
             changed the CFA to the frame pointer this operation
             need not be annotated if frame pointer is needed.
             Always move through unspec, see PR50063.
             For meaning of irq_state see movhi_sp_r insn.  */

          if (cfun->machine->is_interrupt)
            irq_state = 1;

          if (TARGET_NO_INTERRUPTS
              || cfun->machine->is_signal
              || cfun->machine->is_OS_main)
            irq_state = 0;

          if (AVR_HAVE_8BIT_SP)
            irq_state = 2;

          insn = emit_insn (gen_movhi_sp_r (stack_pointer_rtx,
                                            fp, GEN_INT (irq_state)));
          if (!frame_pointer_needed)
            {
              RTX_FRAME_RELATED_P (insn) = 1;
              add_reg_note (insn, REG_CFA_ADJUST_CFA,
                            gen_rtx_SET (VOIDmode, stack_pointer_rtx,
                                         plus_constant (Pmode,
                                                        stack_pointer_rtx,
                                                        -size_cfa)));
            }

          fp_plus_insns = get_insns ();
          end_sequence ();

          /************  Method 2: Adjust Stack pointer  ************/

          /* Stack adjustment by means of RCALL . and/or PUSH __TMP_REG__
             can only handle specific offsets.  */

          if (avr_sp_immediate_operand (gen_int_mode (-size, HImode), HImode))
            {
              rtx sp_plus_insns;

              start_sequence ();

              insn = emit_move_insn (stack_pointer_rtx,
                                     plus_constant (Pmode, stack_pointer_rtx,
                                                    -size));
              RTX_FRAME_RELATED_P (insn) = 1;
              add_reg_note (insn, REG_CFA_ADJUST_CFA,
                            gen_rtx_SET (VOIDmode, stack_pointer_rtx,
                                         plus_constant (Pmode,
                                                        stack_pointer_rtx,
                                                        -size_cfa)));
              if (frame_pointer_needed)
                {
                  insn = emit_move_insn (fp, stack_pointer_rtx);
                  RTX_FRAME_RELATED_P (insn) = 1;
                }

              sp_plus_insns = get_insns ();
              end_sequence ();

              /************ Use shortest method  ************/

              emit_insn (get_sequence_length (sp_plus_insns)
                         < get_sequence_length (fp_plus_insns)
                         ? sp_plus_insns
                         : fp_plus_insns);
            }
          else
            {
              emit_insn (fp_plus_insns);
            }

          cfun->machine->stack_usage += size_cfa;
        } /* !minimize && size != 0 */
    } /* !minimize */
}


/*  Output function prologue.  */

void
avr_expand_prologue (void)
{
  HARD_REG_SET set;
  HOST_WIDE_INT size;

  size = get_frame_size() + avr_outgoing_args_size();

  cfun->machine->stack_usage = 0;

  /* Prologue: naked.  */
  if (cfun->machine->is_naked)
    {
      return;
    }

  avr_regs_to_save (&set);

  if (cfun->machine->is_interrupt || cfun->machine->is_signal)
    {
      /* Enable interrupts.  */
      if (cfun->machine->is_interrupt)
        emit_insn (gen_enable_interrupt ());

      /* Push zero reg.  */
      emit_push_byte (ZERO_REGNO, true);

      /* Push tmp reg.  */
      emit_push_byte (TMP_REGNO, true);

      /* Push SREG.  */
      /* ??? There's no dwarf2 column reserved for SREG.  */
      emit_push_sfr (sreg_rtx, false, false /* clr */);

      /* Clear zero reg.  */
      emit_move_insn (zero_reg_rtx, const0_rtx);

      /* Prevent any attempt to delete the setting of ZERO_REG!  */
      emit_use (zero_reg_rtx);

      /* Push and clear RAMPD/X/Y/Z if present and low-part register is used.
         ??? There are no dwarf2 columns reserved for RAMPD/X/Y/Z.  */

      if (AVR_HAVE_RAMPD)
        emit_push_sfr (rampd_rtx, false /* frame-related */, true /* clr */);

      if (AVR_HAVE_RAMPX
          && TEST_HARD_REG_BIT (set, REG_X)
          && TEST_HARD_REG_BIT (set, REG_X + 1))
        {
          emit_push_sfr (rampx_rtx, false /* frame-related */, true /* clr */);
        }

      if (AVR_HAVE_RAMPY
          && (frame_pointer_needed
              || (TEST_HARD_REG_BIT (set, REG_Y)
                  && TEST_HARD_REG_BIT (set, REG_Y + 1))))
        {
          emit_push_sfr (rampy_rtx, false /* frame-related */, true /* clr */);
        }

      if (AVR_HAVE_RAMPZ
          && TEST_HARD_REG_BIT (set, REG_Z)
          && TEST_HARD_REG_BIT (set, REG_Z + 1))
        {
          emit_push_sfr (rampz_rtx, false /* frame-related */, AVR_HAVE_RAMPD);
        }
    }  /* is_interrupt is_signal */

  avr_prologue_setup_frame (size, set);

  if (flag_stack_usage_info)
    current_function_static_stack_size = cfun->machine->stack_usage;
}


/* Implement `TARGET_ASM_FUNCTION_END_PROLOGUE'.  */
/* Output summary at end of function prologue.  */

static void
avr_asm_function_end_prologue (FILE *file)
{
  if (cfun->machine->is_naked)
    {
      fputs ("/* prologue: naked */\n", file);
    }
  else
    {
      if (cfun->machine->is_interrupt)
        {
          fputs ("/* prologue: Interrupt */\n", file);
        }
      else if (cfun->machine->is_signal)
        {
          fputs ("/* prologue: Signal */\n", file);
        }
      else
        fputs ("/* prologue: function */\n", file);
    }

  if (ACCUMULATE_OUTGOING_ARGS)
    fprintf (file, "/* outgoing args size = %d */\n",
             avr_outgoing_args_size());

  fprintf (file, "/* frame size = " HOST_WIDE_INT_PRINT_DEC " */\n",
                 get_frame_size());
  fprintf (file, "/* stack size = %d */\n",
                 cfun->machine->stack_usage);
  /* Create symbol stack offset here so all functions have it. Add 1 to stack
     usage for offset so that SP + .L__stack_offset = return address.  */
  fprintf (file, ".L__stack_usage = %d\n", cfun->machine->stack_usage);
}


/* Implement `EPILOGUE_USES'.  */

int
avr_epilogue_uses (int regno ATTRIBUTE_UNUSED)
{
  if (reload_completed
      && cfun->machine
      && (cfun->machine->is_interrupt || cfun->machine->is_signal))
    return 1;
  return 0;
}

/*  Helper for avr_expand_epilogue.  Emit a pop of a byte register.  */

static void
emit_pop_byte (unsigned regno)
{
  rtx mem, reg;

  mem = gen_rtx_PRE_INC (HImode, stack_pointer_rtx);
  mem = gen_frame_mem (QImode, mem);
  reg = gen_rtx_REG (QImode, regno);

  emit_insn (gen_rtx_SET (VOIDmode, reg, mem));
}

/*  Output RTL epilogue.  */

void
avr_expand_epilogue (bool sibcall_p)
{
  int reg;
  int live_seq;
  HARD_REG_SET set;
  int minimize;
  HOST_WIDE_INT size;
  bool isr_p = cfun->machine->is_interrupt || cfun->machine->is_signal;

  size = get_frame_size() + avr_outgoing_args_size();

  /* epilogue: naked  */
  if (cfun->machine->is_naked)
    {
      gcc_assert (!sibcall_p);

      emit_jump_insn (gen_return ());
      return;
    }

  avr_regs_to_save (&set);
  live_seq = sequent_regs_live ();

  minimize = (TARGET_CALL_PROLOGUES
              && live_seq
              && !isr_p
              && !cfun->machine->is_OS_task
              && !cfun->machine->is_OS_main);

  if (minimize
      && (live_seq > 4
          || frame_pointer_needed
          || size))
    {
      /*  Get rid of frame.  */

      if (!frame_pointer_needed)
        {
          emit_move_insn (frame_pointer_rtx, stack_pointer_rtx);
        }

      if (size)
        {
          emit_move_insn (frame_pointer_rtx,
                          plus_constant (Pmode, frame_pointer_rtx, size));
        }

      emit_insn (gen_epilogue_restores (gen_int_mode (live_seq, HImode)));
      return;
    }

  if (size)
    {
      /* Try two methods to adjust stack and select shortest.  */

      int irq_state = -1;
      rtx fp, my_fp;
      rtx fp_plus_insns;
      HOST_WIDE_INT size_max;

      gcc_assert (frame_pointer_needed
                  || !isr_p
                  || !crtl->is_leaf);

      fp = my_fp = (frame_pointer_needed
                    ? frame_pointer_rtx
                    : gen_rtx_REG (Pmode, REG_X));

      if (AVR_HAVE_8BIT_SP)
        {
          /* The high byte (r29) does not change:
             Prefer SUBI (1 cycle) over SBIW (2 cycles).  */

          my_fp = all_regs_rtx[FRAME_POINTER_REGNUM];
        }

      /* For rationale see comment in prologue generation.  */

      size_max = (HOST_WIDE_INT) GET_MODE_MASK (GET_MODE (my_fp));
      if (size > size_max)
        size = size_max;
      size = trunc_int_for_mode (size, GET_MODE (my_fp));

      /********** Method 1: Adjust fp register  **********/

      start_sequence ();

      if (!frame_pointer_needed)
        emit_move_insn (fp, stack_pointer_rtx);

      emit_move_insn (my_fp, plus_constant (GET_MODE (my_fp), my_fp, size));

      /* Copy to stack pointer.  */

      if (TARGET_NO_INTERRUPTS)
        irq_state = 0;

      if (AVR_HAVE_8BIT_SP)
        irq_state = 2;

      emit_insn (gen_movhi_sp_r (stack_pointer_rtx, fp,
                                 GEN_INT (irq_state)));

      fp_plus_insns = get_insns ();
      end_sequence ();

      /********** Method 2: Adjust Stack pointer  **********/

      if (avr_sp_immediate_operand (gen_int_mode (size, HImode), HImode))
        {
          rtx sp_plus_insns;

          start_sequence ();

          emit_move_insn (stack_pointer_rtx,
                          plus_constant (Pmode, stack_pointer_rtx, size));

          sp_plus_insns = get_insns ();
          end_sequence ();

          /************ Use shortest method  ************/

          emit_insn (get_sequence_length (sp_plus_insns)
                     < get_sequence_length (fp_plus_insns)
                     ? sp_plus_insns
                     : fp_plus_insns);
        }
      else
        emit_insn (fp_plus_insns);
    } /* size != 0 */

  if (frame_pointer_needed
      && !(cfun->machine->is_OS_task || cfun->machine->is_OS_main))
    {
      /* Restore previous frame_pointer.  See avr_expand_prologue for
         rationale for not using pophi.  */

      emit_pop_byte (REG_Y + 1);
      emit_pop_byte (REG_Y);
    }

  /* Restore used registers.  */

  for (reg = 31; reg >= 0; --reg)
    if (TEST_HARD_REG_BIT (set, reg))
      emit_pop_byte (reg);

  if (isr_p)
    {
      /* Restore RAMPZ/Y/X/D using tmp_reg as scratch.
         The conditions to restore them must be tha same as in prologue.  */

      if (AVR_HAVE_RAMPZ
          && TEST_HARD_REG_BIT (set, REG_Z)
          && TEST_HARD_REG_BIT (set, REG_Z + 1))
        {
          emit_pop_byte (TMP_REGNO);
          emit_move_insn (rampz_rtx, tmp_reg_rtx);
        }

      if (AVR_HAVE_RAMPY
          && (frame_pointer_needed
              || (TEST_HARD_REG_BIT (set, REG_Y)
                  && TEST_HARD_REG_BIT (set, REG_Y + 1))))
        {
          emit_pop_byte (TMP_REGNO);
          emit_move_insn (rampy_rtx, tmp_reg_rtx);
        }

      if (AVR_HAVE_RAMPX
          && TEST_HARD_REG_BIT (set, REG_X)
          && TEST_HARD_REG_BIT (set, REG_X + 1))
        {
          emit_pop_byte (TMP_REGNO);
          emit_move_insn (rampx_rtx, tmp_reg_rtx);
        }

      if (AVR_HAVE_RAMPD)
        {
          emit_pop_byte (TMP_REGNO);
          emit_move_insn (rampd_rtx, tmp_reg_rtx);
        }

      /* Restore SREG using tmp_reg as scratch.  */

      emit_pop_byte (TMP_REGNO);
      emit_move_insn (sreg_rtx, tmp_reg_rtx);

      /* Restore tmp REG.  */
      emit_pop_byte (TMP_REGNO);

      /* Restore zero REG.  */
      emit_pop_byte (ZERO_REGNO);
    }

  if (!sibcall_p)
    emit_jump_insn (gen_return ());
}


/* Implement `TARGET_ASM_FUNCTION_BEGIN_EPILOGUE'.  */

static void
avr_asm_function_begin_epilogue (FILE *file)
{
  fprintf (file, "/* epilogue start */\n");
}


/* Implement `TARGET_CANNOT_MODITY_JUMPS_P'.  */

static bool
avr_cannot_modify_jumps_p (void)
{

  /* Naked Functions must not have any instructions after
     their epilogue, see PR42240 */

  if (reload_completed
      && cfun->machine
      && cfun->machine->is_naked)
    {
      return true;
    }

  return false;
}


/* Implement `TARGET_MODE_DEPENDENT_ADDRESS_P'.  */

static bool
avr_mode_dependent_address_p (const_rtx addr ATTRIBUTE_UNUSED, addr_space_t as)
{
  /* FIXME:  Non-generic addresses are not mode-dependent in themselves.
       This hook just serves to hack around PR rtl-optimization/52543 by
       claiming that non-generic addresses were mode-dependent so that
       lower-subreg.c will skip these addresses.  lower-subreg.c sets up fake
       RTXes to probe SET and MEM costs and assumes that MEM is always in the
       generic address space which is not true.  */

  return !ADDR_SPACE_GENERIC_P (as);
}


/* Helper function for `avr_legitimate_address_p'.  */

static inline bool
avr_reg_ok_for_addr_p (rtx reg, addr_space_t as,
                       RTX_CODE outer_code, bool strict)
{
  return (REG_P (reg)
          && (avr_regno_mode_code_ok_for_base_p (REGNO (reg), QImode,
                                                 as, outer_code, UNKNOWN)
              || (!strict
                  && REGNO (reg) >= FIRST_PSEUDO_REGISTER)));
}


/* Return nonzero if X (an RTX) is a legitimate memory address on the target
   machine for a memory operand of mode MODE.  */

static bool
avr_legitimate_address_p (enum machine_mode mode, rtx x, bool strict)
{
  bool ok = CONSTANT_ADDRESS_P (x);

  switch (GET_CODE (x))
    {
    case REG:
      ok = avr_reg_ok_for_addr_p (x, ADDR_SPACE_GENERIC,
                                  MEM, strict);

      if (strict
          && GET_MODE_SIZE (mode) > 4
          && REG_X == REGNO (x))
        {
          ok = false;
        }
      break;

    case POST_INC:
    case PRE_DEC:
      ok = avr_reg_ok_for_addr_p (XEXP (x, 0), ADDR_SPACE_GENERIC,
                                  GET_CODE (x), strict);
      break;

    case PLUS:
      {
        rtx reg = XEXP (x, 0);
        rtx op1 = XEXP (x, 1);

        if (REG_P (reg)
            && CONST_INT_P (op1)
            && INTVAL (op1) >= 0)
          {
            bool fit = IN_RANGE (INTVAL (op1), 0, MAX_LD_OFFSET (mode));

            if (fit)
              {
                ok = (! strict
                      || avr_reg_ok_for_addr_p (reg, ADDR_SPACE_GENERIC,
                                                PLUS, strict));

                if (reg == frame_pointer_rtx
                    || reg == arg_pointer_rtx)
                  {
                    ok = true;
                  }
              }
            else if (frame_pointer_needed
                     && reg == frame_pointer_rtx)
              {
                ok = true;
              }
          }
      }
      break;

    default:
      break;
    }

  if (avr_log.legitimate_address_p)
    {
      avr_edump ("\n%?: ret=%d, mode=%m strict=%d "
                 "reload_completed=%d reload_in_progress=%d %s:",
                 ok, mode, strict, reload_completed, reload_in_progress,
                 reg_renumber ? "(reg_renumber)" : "");

      if (GET_CODE (x) == PLUS
          && REG_P (XEXP (x, 0))
          && CONST_INT_P (XEXP (x, 1))
          && IN_RANGE (INTVAL (XEXP (x, 1)), 0, MAX_LD_OFFSET (mode))
          && reg_renumber)
        {
          avr_edump ("(r%d ---> r%d)", REGNO (XEXP (x, 0)),
                     true_regnum (XEXP (x, 0)));
        }

      avr_edump ("\n%r\n", x);
    }

  return ok;
}


/* Former implementation of TARGET_LEGITIMIZE_ADDRESS,
   now only a helper for avr_addr_space_legitimize_address.  */
/* Attempts to replace X with a valid
   memory address for an operand of mode MODE  */

static rtx
avr_legitimize_address (rtx x, rtx oldx, enum machine_mode mode)
{
  bool big_offset_p = false;

  x = oldx;

  if (GET_CODE (oldx) == PLUS
      && REG_P (XEXP (oldx, 0)))
    {
      if (REG_P (XEXP (oldx, 1)))
        x = force_reg (GET_MODE (oldx), oldx);
      else if (CONST_INT_P (XEXP (oldx, 1)))
        {
          int offs = INTVAL (XEXP (oldx, 1));
          if (frame_pointer_rtx != XEXP (oldx, 0)
              && offs > MAX_LD_OFFSET (mode))
            {
              big_offset_p = true;
              x = force_reg (GET_MODE (oldx), oldx);
            }
        }
    }

  if (avr_log.legitimize_address)
    {
      avr_edump ("\n%?: mode=%m\n %r\n", mode, oldx);

      if (x != oldx)
        avr_edump (" %s --> %r\n", big_offset_p ? "(big offset)" : "", x);
    }

  return x;
}


/* Implement `LEGITIMIZE_RELOAD_ADDRESS'.  */
/* This will allow register R26/27 to be used where it is no worse than normal
   base pointers R28/29 or R30/31.  For example, if base offset is greater
   than 63 bytes or for R++ or --R addressing.  */

rtx
avr_legitimize_reload_address (rtx *px, enum machine_mode mode,
                               int opnum, int type, int addr_type,
                               int ind_levels ATTRIBUTE_UNUSED,
                               rtx (*mk_memloc)(rtx,int))
{
  rtx x = *px;

  if (avr_log.legitimize_reload_address)
    avr_edump ("\n%?:%m %r\n", mode, x);

  if (1 && (GET_CODE (x) == POST_INC
            || GET_CODE (x) == PRE_DEC))
    {
      push_reload (XEXP (x, 0), XEXP (x, 0), &XEXP (x, 0), &XEXP (x, 0),
                   POINTER_REGS, GET_MODE (x), GET_MODE (x), 0, 0,
                   opnum, RELOAD_OTHER);

      if (avr_log.legitimize_reload_address)
        avr_edump (" RCLASS.1 = %R\n IN = %r\n OUT = %r\n",
                   POINTER_REGS, XEXP (x, 0), XEXP (x, 0));

      return x;
    }

  if (GET_CODE (x) == PLUS
      && REG_P (XEXP (x, 0))
      && 0 == reg_equiv_constant (REGNO (XEXP (x, 0)))
      && CONST_INT_P (XEXP (x, 1))
      && INTVAL (XEXP (x, 1)) >= 1)
    {
      bool fit = INTVAL (XEXP (x, 1)) <= MAX_LD_OFFSET (mode);

      if (fit)
        {
          if (reg_equiv_address (REGNO (XEXP (x, 0))) != 0)
            {
              int regno = REGNO (XEXP (x, 0));
              rtx mem = mk_memloc (x, regno);

              push_reload (XEXP (mem, 0), NULL_RTX, &XEXP (mem, 0), NULL,
                           POINTER_REGS, Pmode, VOIDmode, 0, 0,
                           1, (enum reload_type) addr_type);

              if (avr_log.legitimize_reload_address)
                avr_edump (" RCLASS.2 = %R\n IN = %r\n OUT = %r\n",
                           POINTER_REGS, XEXP (mem, 0), NULL_RTX);

              push_reload (mem, NULL_RTX, &XEXP (x, 0), NULL,
                           BASE_POINTER_REGS, GET_MODE (x), VOIDmode, 0, 0,
                           opnum, (enum reload_type) type);

              if (avr_log.legitimize_reload_address)
                avr_edump (" RCLASS.2 = %R\n IN = %r\n OUT = %r\n",
                           BASE_POINTER_REGS, mem, NULL_RTX);

              return x;
            }
        }
      else if (! (frame_pointer_needed
                  && XEXP (x, 0) == frame_pointer_rtx))
        {
          push_reload (x, NULL_RTX, px, NULL,
                       POINTER_REGS, GET_MODE (x), VOIDmode, 0, 0,
                       opnum, (enum reload_type) type);

          if (avr_log.legitimize_reload_address)
            avr_edump (" RCLASS.3 = %R\n IN = %r\n OUT = %r\n",
                       POINTER_REGS, x, NULL_RTX);

          return x;
        }
    }

  return NULL_RTX;
}


/* Implement `TARGET_SECONDARY_RELOAD' */

static reg_class_t
avr_secondary_reload (bool in_p, rtx x,
                      reg_class_t reload_class ATTRIBUTE_UNUSED,
                      enum machine_mode mode, secondary_reload_info *sri)
{
  if (in_p
      && MEM_P (x)
      && !ADDR_SPACE_GENERIC_P (MEM_ADDR_SPACE (x))
      && ADDR_SPACE_MEMX != MEM_ADDR_SPACE (x))
    {
      /* For the non-generic 16-bit spaces we need a d-class scratch.  */

      switch (mode)
        {
        default:
          gcc_unreachable();

        case QImode:  sri->icode = CODE_FOR_reload_inqi; break;
        case QQmode:  sri->icode = CODE_FOR_reload_inqq; break;
        case UQQmode: sri->icode = CODE_FOR_reload_inuqq; break;

        case HImode:  sri->icode = CODE_FOR_reload_inhi; break;
        case HQmode:  sri->icode = CODE_FOR_reload_inhq; break;
        case HAmode:  sri->icode = CODE_FOR_reload_inha; break;
        case UHQmode: sri->icode = CODE_FOR_reload_inuhq; break;
        case UHAmode: sri->icode = CODE_FOR_reload_inuha; break;

        case PSImode: sri->icode = CODE_FOR_reload_inpsi; break;

        case SImode:  sri->icode = CODE_FOR_reload_insi; break;
        case SFmode:  sri->icode = CODE_FOR_reload_insf; break;
        case SQmode:  sri->icode = CODE_FOR_reload_insq; break;
        case SAmode:  sri->icode = CODE_FOR_reload_insa; break;
        case USQmode: sri->icode = CODE_FOR_reload_inusq; break;
        case USAmode: sri->icode = CODE_FOR_reload_inusa; break;
        }
    }

  return NO_REGS;
}


/* Helper function to print assembler resp. track instruction
   sequence lengths.  Always return "".

   If PLEN == NULL:
       Output assembler code from template TPL with operands supplied
       by OPERANDS.  This is just forwarding to output_asm_insn.

   If PLEN != NULL:
       If N_WORDS >= 0  Add N_WORDS to *PLEN.
       If N_WORDS < 0   Set *PLEN to -N_WORDS.
       Don't output anything.
*/

static const char*
avr_asm_len (const char* tpl, rtx* operands, int* plen, int n_words)
{
  if (NULL == plen)
    {
      output_asm_insn (tpl, operands);
    }
  else
    {
      if (n_words < 0)
        *plen = -n_words;
      else
        *plen += n_words;
    }

  return "";
}


/* Return a pointer register name as a string.  */

static const char*
ptrreg_to_str (int regno)
{
  switch (regno)
    {
    case REG_X: return "X";
    case REG_Y: return "Y";
    case REG_Z: return "Z";
    default:
      output_operand_lossage ("address operand requires constraint for"
                              " X, Y, or Z register");
    }
  return NULL;
}

/* Return the condition name as a string.
   Used in conditional jump constructing  */

static const char*
cond_string (enum rtx_code code)
{
  switch (code)
    {
    case NE:
      return "ne";
    case EQ:
      return "eq";
    case GE:
      if (cc_prev_status.flags & CC_OVERFLOW_UNUSABLE)
        return "pl";
      else
        return "ge";
    case LT:
      if (cc_prev_status.flags & CC_OVERFLOW_UNUSABLE)
        return "mi";
      else
        return "lt";
    case GEU:
      return "sh";
    case LTU:
      return "lo";
    default:
      gcc_unreachable ();
    }

  return "";
}


/* Implement `TARGET_PRINT_OPERAND_ADDRESS'.  */
/* Output ADDR to FILE as address.  */

static void
avr_print_operand_address (FILE *file, rtx addr)
{
  switch (GET_CODE (addr))
    {
    case REG:
      fprintf (file, ptrreg_to_str (REGNO (addr)));
      break;

    case PRE_DEC:
      fprintf (file, "-%s", ptrreg_to_str (REGNO (XEXP (addr, 0))));
      break;

    case POST_INC:
      fprintf (file, "%s+", ptrreg_to_str (REGNO (XEXP (addr, 0))));
      break;

    default:
      if (CONSTANT_ADDRESS_P (addr)
          && text_segment_operand (addr, VOIDmode))
        {
          rtx x = addr;
          if (GET_CODE (x) == CONST)
            x = XEXP (x, 0);
          if (GET_CODE (x) == PLUS && GET_CODE (XEXP (x,1)) == CONST_INT)
            {
              /* Assembler gs() will implant word address.  Make offset
                 a byte offset inside gs() for assembler.  This is
                 needed because the more logical (constant+gs(sym)) is not
                 accepted by gas.  For 128K and smaller devices this is ok.
                 For large devices it will create a trampoline to offset
                 from symbol which may not be what the user really wanted.  */

              fprintf (file, "gs(");
              output_addr_const (file, XEXP (x,0));
              fprintf (file, "+" HOST_WIDE_INT_PRINT_DEC ")",
                       2 * INTVAL (XEXP (x, 1)));
              if (AVR_3_BYTE_PC)
                if (warning (0, "pointer offset from symbol maybe incorrect"))
                  {
                    output_addr_const (stderr, addr);
                    fprintf(stderr,"\n");
                  }
            }
          else
            {
              fprintf (file, "gs(");
              output_addr_const (file, addr);
              fprintf (file, ")");
            }
        }
      else
        output_addr_const (file, addr);
    }
}


/* Implement `TARGET_PRINT_OPERAND_PUNCT_VALID_P'.  */

static bool
avr_print_operand_punct_valid_p (unsigned char code)
{
  return code == '~' || code == '!';
}


/* Implement `TARGET_PRINT_OPERAND'.  */
/* Output X as assembler operand to file FILE.
   For a description of supported %-codes, see top of avr.md.  */

static void
avr_print_operand (FILE *file, rtx x, int code)
{
  int abcd = 0;

  if (code >= 'A' && code <= 'D')
    abcd = code - 'A';

  if (code == '~')
    {
      if (!AVR_HAVE_JMP_CALL)
        fputc ('r', file);
    }
  else if (code == '!')
    {
      if (AVR_HAVE_EIJMP_EICALL)
        fputc ('e', file);
    }
  else if (code == 't'
           || code == 'T')
    {
      static int t_regno = -1;
      static int t_nbits = -1;

      if (REG_P (x) && t_regno < 0 && code == 'T')
        {
          t_regno = REGNO (x);
          t_nbits = GET_MODE_BITSIZE (GET_MODE (x));
        }
      else if (CONST_INT_P (x) && t_regno >= 0
               && IN_RANGE (INTVAL (x), 0, t_nbits - 1))
        {
          int bpos = INTVAL (x);

          fprintf (file, "%s", reg_names[t_regno + bpos / 8]);
          if (code == 'T')
            fprintf (file, ",%d", bpos % 8);

          t_regno = -1;
        }
      else
        fatal_insn ("operands to %T/%t must be reg + const_int:", x);
    }
  else if (REG_P (x))
    {
      if (x == zero_reg_rtx)
        fprintf (file, "__zero_reg__");
      else if (code == 'r' && REGNO (x) < 32)
        fprintf (file, "%d", (int) REGNO (x));
      else
        fprintf (file, reg_names[REGNO (x) + abcd]);
    }
  else if (CONST_INT_P (x))
    {
      HOST_WIDE_INT ival = INTVAL (x);

      if ('i' != code)
        fprintf (file, HOST_WIDE_INT_PRINT_DEC, ival + abcd);
      else if (low_io_address_operand (x, VOIDmode)
               || high_io_address_operand (x, VOIDmode))
        {
          if (AVR_HAVE_RAMPZ && ival == avr_addr.rampz)
            fprintf (file, "__RAMPZ__");
          else if (AVR_HAVE_RAMPY && ival == avr_addr.rampy)
            fprintf (file, "__RAMPY__");
          else if (AVR_HAVE_RAMPX && ival == avr_addr.rampx)
            fprintf (file, "__RAMPX__");
          else if (AVR_HAVE_RAMPD && ival == avr_addr.rampd)
            fprintf (file, "__RAMPD__");
          else if (AVR_XMEGA && ival == avr_addr.ccp)
            fprintf (file, "__CCP__");
          else if (ival == avr_addr.sreg)   fprintf (file, "__SREG__");
          else if (ival == avr_addr.sp_l)   fprintf (file, "__SP_L__");
          else if (ival == avr_addr.sp_h)   fprintf (file, "__SP_H__");
          else
            {
              fprintf (file, HOST_WIDE_INT_PRINT_HEX,
                       ival - avr_current_arch->sfr_offset);
            }
        }
      else
        fatal_insn ("bad address, not an I/O address:", x);
    }
  else if (MEM_P (x))
    {
      rtx addr = XEXP (x, 0);

      if (code == 'm')
        {
          if (!CONSTANT_P (addr))
            fatal_insn ("bad address, not a constant:", addr);
          /* Assembler template with m-code is data - not progmem section */
          if (text_segment_operand (addr, VOIDmode))
            if (warning (0, "accessing data memory with"
                         " program memory address"))
              {
                output_addr_const (stderr, addr);
                fprintf(stderr,"\n");
              }
          output_addr_const (file, addr);
        }
      else if (code == 'i')
        {
          avr_print_operand (file, addr, 'i');
        }
      else if (code == 'o')
        {
          if (GET_CODE (addr) != PLUS)
            fatal_insn ("bad address, not (reg+disp):", addr);

          avr_print_operand (file, XEXP (addr, 1), 0);
        }
      else if (code == 'p' || code == 'r')
        {
          if (GET_CODE (addr) != POST_INC && GET_CODE (addr) != PRE_DEC)
            fatal_insn ("bad address, not post_inc or pre_dec:", addr);

          if (code == 'p')
            avr_print_operand_address (file, XEXP (addr, 0));  /* X, Y, Z */
          else
            avr_print_operand (file, XEXP (addr, 0), 0);  /* r26, r28, r30 */
        }
      else if (GET_CODE (addr) == PLUS)
        {
          avr_print_operand_address (file, XEXP (addr,0));
          if (REGNO (XEXP (addr, 0)) == REG_X)
            fatal_insn ("internal compiler error.  Bad address:"
                        ,addr);
          fputc ('+', file);
          avr_print_operand (file, XEXP (addr,1), code);
        }
      else
        avr_print_operand_address (file, addr);
    }
  else if (code == 'i')
    {
      fatal_insn ("bad address, not an I/O address:", x);
    }
  else if (code == 'x')
    {
      /* Constant progmem address - like used in jmp or call */
      if (0 == text_segment_operand (x, VOIDmode))
        if (warning (0, "accessing program memory"
                     " with data memory address"))
          {
            output_addr_const (stderr, x);
            fprintf(stderr,"\n");
          }
      /* Use normal symbol for direct address no linker trampoline needed */
      output_addr_const (file, x);
    }
  else if (CONST_FIXED_P (x))
    {
      HOST_WIDE_INT ival = INTVAL (avr_to_int_mode (x));
      if (code != 0)
        output_operand_lossage ("Unsupported code '%c' for fixed-point:",
                                code);
      fprintf (file, HOST_WIDE_INT_PRINT_DEC, ival);
    }
  else if (GET_CODE (x) == CONST_DOUBLE)
    {
      long val;
      REAL_VALUE_TYPE rv;
      if (GET_MODE (x) != SFmode)
        fatal_insn ("internal compiler error.  Unknown mode:", x);
      REAL_VALUE_FROM_CONST_DOUBLE (rv, x);
      REAL_VALUE_TO_TARGET_SINGLE (rv, val);
      fprintf (file, "0x%lx", val);
    }
  else if (GET_CODE (x) == CONST_STRING)
    fputs (XSTR (x, 0), file);
  else if (code == 'j')
    fputs (cond_string (GET_CODE (x)), file);
  else if (code == 'k')
    fputs (cond_string (reverse_condition (GET_CODE (x))), file);
  else
    avr_print_operand_address (file, x);
}


/* Worker function for `NOTICE_UPDATE_CC'.  */
/* Update the condition code in the INSN.  */

void
avr_notice_update_cc (rtx body ATTRIBUTE_UNUSED, rtx insn)
{
  rtx set;
  enum attr_cc cc = get_attr_cc (insn);

  switch (cc)
    {
    default:
      break;

    case CC_PLUS:
    case CC_LDI:
      {
        rtx *op = recog_data.operand;
        int len_dummy, icc;

        /* Extract insn's operands.  */
        extract_constrain_insn_cached (insn);

        switch (cc)
          {
          default:
            gcc_unreachable();

          case CC_PLUS:
            avr_out_plus (insn, op, &len_dummy, &icc);
            cc = (enum attr_cc) icc;
            break;

          case CC_LDI:

            cc = (op[1] == CONST0_RTX (GET_MODE (op[0]))
                  && reg_overlap_mentioned_p (op[0], zero_reg_rtx))
              /* Loading zero-reg with 0 uses CLR and thus clobbers cc0.  */
              ? CC_CLOBBER
              /* Any other "r,rL" combination does not alter cc0.  */
              : CC_NONE;

            break;
          } /* inner switch */

        break;
      }
    } /* outer swicth */

  switch (cc)
    {
    default:
      /* Special values like CC_OUT_PLUS from above have been
         mapped to "standard" CC_* values so we never come here.  */

      gcc_unreachable();
      break;

    case CC_NONE:
      /* Insn does not affect CC at all.  */
      break;

    case CC_SET_N:
      CC_STATUS_INIT;
      break;

    case CC_SET_ZN:
      set = single_set (insn);
      CC_STATUS_INIT;
      if (set)
        {
          cc_status.flags |= CC_NO_OVERFLOW;
          cc_status.value1 = SET_DEST (set);
        }
      break;

    case CC_SET_VZN:
      /* Insn like INC, DEC, NEG that set Z,N,V.  We currently don't make use
         of this combination, cf. also PR61055.  */
      CC_STATUS_INIT;
      break;

    case CC_SET_CZN:
      /* Insn sets the Z,N,C flags of CC to recog_operand[0].
         The V flag may or may not be known but that's ok because
         alter_cond will change tests to use EQ/NE.  */
      set = single_set (insn);
      CC_STATUS_INIT;
      if (set)
        {
          cc_status.value1 = SET_DEST (set);
          cc_status.flags |= CC_OVERFLOW_UNUSABLE;
        }
      break;

    case CC_COMPARE:
      set = single_set (insn);
      CC_STATUS_INIT;
      if (set)
        cc_status.value1 = SET_SRC (set);
      break;

    case CC_CLOBBER:
      /* Insn doesn't leave CC in a usable state.  */
      CC_STATUS_INIT;
      break;
    }
}

/* Choose mode for jump insn:
   1 - relative jump in range -63 <= x <= 62 ;
   2 - relative jump in range -2046 <= x <= 2045 ;
   3 - absolute jump (only for ATmega[16]03).  */

int
avr_jump_mode (rtx x, rtx insn)
{
  int dest_addr = INSN_ADDRESSES (INSN_UID (GET_CODE (x) == LABEL_REF
                                            ? XEXP (x, 0) : x));
  int cur_addr = INSN_ADDRESSES (INSN_UID (insn));
  int jump_distance = cur_addr - dest_addr;

  if (-63 <= jump_distance && jump_distance <= 62)
    return 1;
  else if (-2046 <= jump_distance && jump_distance <= 2045)
    return 2;
  else if (AVR_HAVE_JMP_CALL)
    return 3;

  return 2;
}

/* Return an AVR condition jump commands.
   X is a comparison RTX.
   LEN is a number returned by avr_jump_mode function.
   If REVERSE nonzero then condition code in X must be reversed.  */

const char*
ret_cond_branch (rtx x, int len, int reverse)
{
  RTX_CODE cond = reverse ? reverse_condition (GET_CODE (x)) : GET_CODE (x);

  switch (cond)
    {
    case GT:
      if (cc_prev_status.flags & CC_OVERFLOW_UNUSABLE)
	return (len == 1 ? ("breq .+2" CR_TAB
			    "brpl %0") :
		len == 2 ? ("breq .+4" CR_TAB
			    "brmi .+2" CR_TAB
			    "rjmp %0") :
		("breq .+6" CR_TAB
		 "brmi .+4" CR_TAB
		 "jmp %0"));

      else
	return (len == 1 ? ("breq .+2" CR_TAB
			    "brge %0") :
		len == 2 ? ("breq .+4" CR_TAB
			    "brlt .+2" CR_TAB
			    "rjmp %0") :
		("breq .+6" CR_TAB
		 "brlt .+4" CR_TAB
		 "jmp %0"));
    case GTU:
      return (len == 1 ? ("breq .+2" CR_TAB
                          "brsh %0") :
              len == 2 ? ("breq .+4" CR_TAB
                          "brlo .+2" CR_TAB
                          "rjmp %0") :
              ("breq .+6" CR_TAB
               "brlo .+4" CR_TAB
               "jmp %0"));
    case LE:
      if (cc_prev_status.flags & CC_OVERFLOW_UNUSABLE)
	return (len == 1 ? ("breq %0" CR_TAB
			    "brmi %0") :
		len == 2 ? ("breq .+2" CR_TAB
			    "brpl .+2" CR_TAB
			    "rjmp %0") :
		("breq .+2" CR_TAB
		 "brpl .+4" CR_TAB
		 "jmp %0"));
      else
	return (len == 1 ? ("breq %0" CR_TAB
			    "brlt %0") :
		len == 2 ? ("breq .+2" CR_TAB
			    "brge .+2" CR_TAB
			    "rjmp %0") :
		("breq .+2" CR_TAB
		 "brge .+4" CR_TAB
		 "jmp %0"));
    case LEU:
      return (len == 1 ? ("breq %0" CR_TAB
                          "brlo %0") :
              len == 2 ? ("breq .+2" CR_TAB
                          "brsh .+2" CR_TAB
			  "rjmp %0") :
              ("breq .+2" CR_TAB
               "brsh .+4" CR_TAB
	       "jmp %0"));
    default:
      if (reverse)
	{
	  switch (len)
	    {
	    case 1:
	      return "br%k1 %0";
	    case 2:
	      return ("br%j1 .+2" CR_TAB
		      "rjmp %0");
	    default:
	      return ("br%j1 .+4" CR_TAB
		      "jmp %0");
	    }
	}
      else
        {
          switch (len)
            {
            case 1:
              return "br%j1 %0";
            case 2:
              return ("br%k1 .+2" CR_TAB
                      "rjmp %0");
            default:
              return ("br%k1 .+4" CR_TAB
                      "jmp %0");
            }
        }
    }
  return "";
}


/* Worker function for `FINAL_PRESCAN_INSN'.  */
/* Output insn cost for next insn.  */

void
avr_final_prescan_insn (rtx insn, rtx *operand ATTRIBUTE_UNUSED,
                        int num_operands ATTRIBUTE_UNUSED)
{
  if (avr_log.rtx_costs)
    {
      rtx set = single_set (insn);

      if (set)
        fprintf (asm_out_file, "/* DEBUG: cost = %d.  */\n",
                 set_src_cost (SET_SRC (set), optimize_insn_for_speed_p ()));
      else
        fprintf (asm_out_file, "/* DEBUG: pattern-cost = %d.  */\n",
                 rtx_cost (PATTERN (insn), INSN, 0,
                           optimize_insn_for_speed_p()));
    }
}

/* Return 0 if undefined, 1 if always true or always false.  */

int
avr_simplify_comparison_p (enum machine_mode mode, RTX_CODE op, rtx x)
{
  unsigned int max = (mode == QImode ? 0xff :
                      mode == HImode ? 0xffff :
                      mode == PSImode ? 0xffffff :
                      mode == SImode ? 0xffffffff : 0);
  if (max && op && CONST_INT_P (x))
    {
      if (unsigned_condition (op) != op)
        max >>= 1;

      if (max != (INTVAL (x) & max)
          && INTVAL (x) != 0xff)
        return 1;
    }
  return 0;
}


/* Worker function for `FUNCTION_ARG_REGNO_P'.  */
/* Returns nonzero if REGNO is the number of a hard
   register in which function arguments are sometimes passed.  */

int
avr_function_arg_regno_p(int r)
{
  return (r >= 8 && r <= 25);
}


/* Worker function for `INIT_CUMULATIVE_ARGS'.  */
/* Initializing the variable cum for the state at the beginning
   of the argument list.  */

void
avr_init_cumulative_args (CUMULATIVE_ARGS *cum, tree fntype, rtx libname,
                          tree fndecl ATTRIBUTE_UNUSED)
{
  cum->nregs = 18;
  cum->regno = FIRST_CUM_REG;
  if (!libname && stdarg_p (fntype))
    cum->nregs = 0;

  /* Assume the calle may be tail called */

  cfun->machine->sibcall_fails = 0;
}

/* Returns the number of registers to allocate for a function argument.  */

static int
avr_num_arg_regs (enum machine_mode mode, const_tree type)
{
  int size;

  if (mode == BLKmode)
    size = int_size_in_bytes (type);
  else
    size = GET_MODE_SIZE (mode);

  /* Align all function arguments to start in even-numbered registers.
     Odd-sized arguments leave holes above them.  */

  return (size + 1) & ~1;
}


/* Implement `TARGET_FUNCTION_ARG'.  */
/* Controls whether a function argument is passed
   in a register, and which register.  */

static rtx
avr_function_arg (cumulative_args_t cum_v, enum machine_mode mode,
                  const_tree type, bool named ATTRIBUTE_UNUSED)
{
  CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
  int bytes = avr_num_arg_regs (mode, type);

  if (cum->nregs && bytes <= cum->nregs)
    return gen_rtx_REG (mode, cum->regno - bytes);

  return NULL_RTX;
}


/* Implement `TARGET_FUNCTION_ARG_ADVANCE'.  */
/* Update the summarizer variable CUM to advance past an argument
   in the argument list.  */

static void
avr_function_arg_advance (cumulative_args_t cum_v, enum machine_mode mode,
                          const_tree type, bool named ATTRIBUTE_UNUSED)
{
  CUMULATIVE_ARGS *cum = get_cumulative_args (cum_v);
  int bytes = avr_num_arg_regs (mode, type);

  cum->nregs -= bytes;
  cum->regno -= bytes;

  /* A parameter is being passed in a call-saved register.  As the original
     contents of these regs has to be restored before leaving the function,
     a function must not pass arguments in call-saved regs in order to get
     tail-called.  */

  if (cum->regno >= 8
      && cum->nregs >= 0
      && !call_used_regs[cum->regno])
    {
      /* FIXME: We ship info on failing tail-call in struct machine_function.
         This uses internals of calls.c:expand_call() and the way args_so_far
         is used.  targetm.function_ok_for_sibcall() needs to be extended to
         pass &args_so_far, too.  At present, CUMULATIVE_ARGS is target
         dependent so that such an extension is not wanted.  */

      cfun->machine->sibcall_fails = 1;
    }

  /* Test if all registers needed by the ABI are actually available.  If the
     user has fixed a GPR needed to pass an argument, an (implicit) function
     call will clobber that fixed register.  See PR45099 for an example.  */

  if (cum->regno >= 8
      && cum->nregs >= 0)
    {
      int regno;

      for (regno = cum->regno; regno < cum->regno + bytes; regno++)
        if (fixed_regs[regno])
          warning (0, "fixed register %s used to pass parameter to function",
                   reg_names[regno]);
    }

  if (cum->nregs <= 0)
    {
      cum->nregs = 0;
      cum->regno = FIRST_CUM_REG;
    }
}

/* Implement `TARGET_FUNCTION_OK_FOR_SIBCALL' */
/* Decide whether we can make a sibling call to a function.  DECL is the
   declaration of the function being targeted by the call and EXP is the
   CALL_EXPR representing the call.  */

static bool
avr_function_ok_for_sibcall (tree decl_callee, tree exp_callee)
{
  tree fntype_callee;

  /* Tail-calling must fail if callee-saved regs are used to pass
     function args.  We must not tail-call when `epilogue_restores'
     is used.  Unfortunately, we cannot tell at this point if that
     actually will happen or not, and we cannot step back from
     tail-calling.  Thus, we inhibit tail-calling with -mcall-prologues.  */

  if (cfun->machine->sibcall_fails
      || TARGET_CALL_PROLOGUES)
    {
      return false;
    }

  fntype_callee = TREE_TYPE (CALL_EXPR_FN (exp_callee));

  if (decl_callee)
    {
      decl_callee = TREE_TYPE (decl_callee);
    }
  else
    {
      decl_callee = fntype_callee;

      while (FUNCTION_TYPE != TREE_CODE (decl_callee)
             && METHOD_TYPE != TREE_CODE (decl_callee))
        {
          decl_callee = TREE_TYPE (decl_callee);
        }
    }

  /* Ensure that caller and callee have compatible epilogues */

  if (cfun->machine->is_interrupt
      || cfun->machine->is_signal
      || cfun->machine->is_naked
      || avr_naked_function_p (decl_callee)
      /* FIXME: For OS_task and OS_main, this might be over-conservative.  */
      || (avr_OS_task_function_p (decl_callee)
          != cfun->machine->is_OS_task)
      || (avr_OS_main_function_p (decl_callee)
          != cfun->machine->is_OS_main))
    {
      return false;
    }

  return true;
}

/***********************************************************************
  Functions for outputting various mov's for a various modes
************************************************************************/

/* Return true if a value of mode MODE is read from flash by
   __load_* function from libgcc.  */

bool
avr_load_libgcc_p (rtx op)
{
  enum machine_mode mode = GET_MODE (op);
  int n_bytes = GET_MODE_SIZE (mode);

  return (n_bytes > 2
          && !AVR_HAVE_LPMX
          && avr_mem_flash_p (op));
}

/* Return true if a value of mode MODE is read by __xload_* function.  */

bool
avr_xload_libgcc_p (enum machine_mode mode)
{
  int n_bytes = GET_MODE_SIZE (mode);

  return (n_bytes > 1
          || avr_current_device->n_flash > 1);
}


/* Fixme: This is a hack because secondary reloads don't works as expected.

   Find an unused d-register to be used as scratch in INSN.
   EXCLUDE is either NULL_RTX or some register. In the case where EXCLUDE
   is a register, skip all possible return values that overlap EXCLUDE.
   The policy for the returned register is similar to that of
   `reg_unused_after', i.e. the returned register may overlap the SET_DEST
   of INSN.

   Return a QImode d-register or NULL_RTX if nothing found.  */

static rtx
avr_find_unused_d_reg (rtx insn, rtx exclude)
{
  int regno;
  bool isr_p = (avr_interrupt_function_p (current_function_decl)
                || avr_signal_function_p (current_function_decl));

  for (regno = 16; regno < 32; regno++)
    {
      rtx reg = all_regs_rtx[regno];

      if ((exclude
           && reg_overlap_mentioned_p (exclude, reg))
          || fixed_regs[regno])
        {
          continue;
        }

      /* Try non-live register */

      if (!df_regs_ever_live_p (regno)
          && (TREE_THIS_VOLATILE (current_function_decl)
              || cfun->machine->is_OS_task
              || cfun->machine->is_OS_main
              || (!isr_p && call_used_regs[regno])))
        {
          return reg;
        }

      /* Any live register can be used if it is unused after.
         Prologue/epilogue will care for it as needed.  */

      if (df_regs_ever_live_p (regno)
          && reg_unused_after (insn, reg))
        {
          return reg;
        }
    }

  return NULL_RTX;
}


/* Helper function for the next function in the case where only restricted
   version of LPM instruction is available.  */

static const char*
avr_out_lpm_no_lpmx (rtx insn, rtx *xop, int *plen)
{
  rtx dest = xop[0];
  rtx addr = xop[1];
  int n_bytes = GET_MODE_SIZE (GET_MODE (dest));
  int regno_dest;

  regno_dest = REGNO (dest);

  /* The implicit target register of LPM.  */
  xop[3] = lpm_reg_rtx;

  switch (GET_CODE (addr))
    {
    default:
      gcc_unreachable();

    case REG:

      gcc_assert (REG_Z == REGNO (addr));

      switch (n_bytes)
        {
        default:
          gcc_unreachable();

        case 1:
          avr_asm_len ("%4lpm", xop, plen, 1);

          if (regno_dest != LPM_REGNO)
            avr_asm_len ("mov %0,%3", xop, plen, 1);

          return "";

        case 2:
          if (REGNO (dest) == REG_Z)
            return avr_asm_len ("%4lpm"      CR_TAB
                                "push %3"    CR_TAB
                                "adiw %2,1"  CR_TAB
                                "%4lpm"      CR_TAB
                                "mov %B0,%3" CR_TAB
                                "pop %A0", xop, plen, 6);

          avr_asm_len ("%4lpm"      CR_TAB
                       "mov %A0,%3" CR_TAB
                       "adiw %2,1"  CR_TAB
                       "%4lpm"      CR_TAB
                       "mov %B0,%3", xop, plen, 5);

          if (!reg_unused_after (insn, addr))
            avr_asm_len ("sbiw %2,1", xop, plen, 1);

          break; /* 2 */
        }

      break; /* REG */

    case POST_INC:

      gcc_assert (REG_Z == REGNO (XEXP (addr, 0))
                  && n_bytes <= 4);

      if (regno_dest == LPM_REGNO)
        avr_asm_len ("%4lpm"      CR_TAB
                     "adiw %2,1", xop, plen, 2);
      else
        avr_asm_len ("%4lpm"      CR_TAB
                     "mov %A0,%3" CR_TAB
                     "adiw %2,1", xop, plen, 3);

      if (n_bytes >= 2)
        avr_asm_len ("%4lpm"      CR_TAB
                     "mov %B0,%3" CR_TAB
                     "adiw %2,1", xop, plen, 3);

      if (n_bytes >= 3)
        avr_asm_len ("%4lpm"      CR_TAB
                     "mov %C0,%3" CR_TAB
                     "adiw %2,1", xop, plen, 3);

      if (n_bytes >= 4)
        avr_asm_len ("%4lpm"      CR_TAB
                     "mov %D0,%3" CR_TAB
                     "adiw %2,1", xop, plen, 3);

      break; /* POST_INC */

    } /* switch CODE (addr) */

  return "";
}


/* If PLEN == NULL: Ouput instructions to load a value from a memory location
   OP[1] in AS1 to register OP[0].
   If PLEN != 0 set *PLEN to the length in words of the instruction sequence.
   Return "".  */

const char*
avr_out_lpm (rtx insn, rtx *op, int *plen)
{
  rtx xop[7];
  rtx dest = op[0];
  rtx src = SET_SRC (single_set (insn));
  rtx addr;
  int n_bytes = GET_MODE_SIZE (GET_MODE (dest));
  int segment;
  RTX_CODE code;
  addr_space_t as = MEM_ADDR_SPACE (src);

  if (plen)
    *plen = 0;

  if (MEM_P (dest))
    {
      warning (0, "writing to address space %qs not supported",
               avr_addrspace[MEM_ADDR_SPACE (dest)].name);

      return "";
    }

  addr = XEXP (src, 0);
  code = GET_CODE (addr);

  gcc_assert (REG_P (dest));
  gcc_assert (REG == code || POST_INC == code);

  xop[0] = dest;
  xop[1] = addr;
  xop[2] = lpm_addr_reg_rtx;
  xop[4] = xstring_empty;
  xop[5] = tmp_reg_rtx;
  xop[6] = XEXP (rampz_rtx, 0);

  segment = avr_addrspace[as].segment;

  /* Set RAMPZ as needed.  */

  if (segment)
    {
      xop[4] = GEN_INT (segment);
      xop[3] = avr_find_unused_d_reg (insn, lpm_addr_reg_rtx);

      if (xop[3] != NULL_RTX)
        {
          avr_asm_len ("ldi %3,%4" CR_TAB
                       "out %i6,%3", xop, plen, 2);
        }
      else if (segment == 1)
        {
          avr_asm_len ("clr %5" CR_TAB
                       "inc %5" CR_TAB
                       "out %i6,%5", xop, plen, 3);
        }
      else
        {
          avr_asm_len ("mov %5,%2"         CR_TAB
                       "ldi %2,%4"         CR_TAB
                       "out %i6,%2"  CR_TAB
                       "mov %2,%5", xop, plen, 4);
        }

      xop[4] = xstring_e;

      if (!AVR_HAVE_ELPMX)
        return avr_out_lpm_no_lpmx (insn, xop, plen);
    }
  else if (!AVR_HAVE_LPMX)
    {
      return avr_out_lpm_no_lpmx (insn, xop, plen);
    }

  /* We have [E]LPMX: Output reading from Flash the comfortable way.  */

  switch (GET_CODE (addr))
    {
    default:
      gcc_unreachable();

    case REG:

      gcc_assert (REG_Z == REGNO (addr));

      switch (n_bytes)
        {
        default:
          gcc_unreachable();

        case 1:
          return avr_asm_len ("%4lpm %0,%a2", xop, plen, 1);

        case 2:
          if (REGNO (dest) == REG_Z)
            return avr_asm_len ("%4lpm %5,%a2+" CR_TAB
                                "%4lpm %B0,%a2" CR_TAB
                                "mov %A0,%5", xop, plen, 3);
          else
            {
              avr_asm_len ("%4lpm %A0,%a2+" CR_TAB
                           "%4lpm %B0,%a2", xop, plen, 2);

              if (!reg_unused_after (insn, addr))
                avr_asm_len ("sbiw %2,1", xop, plen, 1);
            }

          break; /* 2 */

        case 3:

          avr_asm_len ("%4lpm %A0,%a2+" CR_TAB
                       "%4lpm %B0,%a2+" CR_TAB
                       "%4lpm %C0,%a2", xop, plen, 3);

          if (!reg_unused_after (insn, addr))
            avr_asm_len ("sbiw %2,2", xop, plen, 1);

          break; /* 3 */

        case 4:

          avr_asm_len ("%4lpm %A0,%a2+" CR_TAB
                       "%4lpm %B0,%a2+", xop, plen, 2);

          if (REGNO (dest) == REG_Z - 2)
            return avr_asm_len ("%4lpm %5,%a2+" CR_TAB
                                "%4lpm %C0,%a2"          CR_TAB
                                "mov %D0,%5", xop, plen, 3);
          else
            {
              avr_asm_len ("%4lpm %C0,%a2+" CR_TAB
                           "%4lpm %D0,%a2", xop, plen, 2);

              if (!reg_unused_after (insn, addr))
                avr_asm_len ("sbiw %2,3", xop, plen, 1);
            }

          break; /* 4 */
        } /* n_bytes */

      break; /* REG */

    case POST_INC:

      gcc_assert (REG_Z == REGNO (XEXP (addr, 0))
                  && n_bytes <= 4);

      avr_asm_len                    ("%4lpm %A0,%a2+", xop, plen, 1);
      if (n_bytes >= 2)  avr_asm_len ("%4lpm %B0,%a2+", xop, plen, 1);
      if (n_bytes >= 3)  avr_asm_len ("%4lpm %C0,%a2+", xop, plen, 1);
      if (n_bytes >= 4)  avr_asm_len ("%4lpm %D0,%a2+", xop, plen, 1);

      break; /* POST_INC */

    } /* switch CODE (addr) */

  if (xop[4] == xstring_e && AVR_HAVE_RAMPD)
    {
      /* Reset RAMPZ to 0 so that EBI devices don't read garbage from RAM.  */

      xop[0] = zero_reg_rtx;
      avr_asm_len ("out %i6,%0", xop, plen, 1);
    }

  return "";
}


/* Worker function for xload_8 insn.  */

const char*
avr_out_xload (rtx insn ATTRIBUTE_UNUSED, rtx *op, int *plen)
{
  rtx xop[4];

  xop[0] = op[0];
  xop[1] = op[1];
  xop[2] = lpm_addr_reg_rtx;
  xop[3] = AVR_HAVE_LPMX ? op[0] : lpm_reg_rtx;

  avr_asm_len (AVR_HAVE_LPMX ? "lpm %3,%a2" : "lpm", xop, plen, -1);

  avr_asm_len ("sbrc %1,7" CR_TAB
               "ld %3,%a2", xop, plen, 2);

  if (REGNO (xop[0]) != REGNO (xop[3]))
    avr_asm_len ("mov %0,%3", xop, plen, 1);

  return "";
}


const char*
output_movqi (rtx insn, rtx operands[], int *plen)
{
  rtx dest = operands[0];
  rtx src = operands[1];

  if (avr_mem_flash_p (src)
      || avr_mem_flash_p (dest))
    {
      return avr_out_lpm (insn, operands, plen);
    }

  gcc_assert (1 == GET_MODE_SIZE (GET_MODE (dest)));

  if (REG_P (dest))
    {
      if (REG_P (src)) /* mov r,r */
        {
          if (test_hard_reg_class (STACK_REG, dest))
            return avr_asm_len ("out %0,%1", operands, plen, -1);
          else if (test_hard_reg_class (STACK_REG, src))
            return avr_asm_len ("in %0,%1", operands, plen, -1);

          return avr_asm_len ("mov %0,%1", operands, plen, -1);
        }
      else if (CONSTANT_P (src))
        {
          output_reload_in_const (operands, NULL_RTX, plen, false);
          return "";
        }
      else if (MEM_P (src))
        return out_movqi_r_mr (insn, operands, plen); /* mov r,m */
    }
  else if (MEM_P (dest))
    {
      rtx xop[2];

      xop[0] = dest;
      xop[1] = src == CONST0_RTX (GET_MODE (dest)) ? zero_reg_rtx : src;

      return out_movqi_mr_r (insn, xop, plen);
    }

  return "";
}


const char *
output_movhi (rtx insn, rtx xop[], int *plen)
{
  rtx dest = xop[0];
  rtx src = xop[1];

  gcc_assert (GET_MODE_SIZE (GET_MODE (dest)) == 2);

  if (avr_mem_flash_p (src)
      || avr_mem_flash_p (dest))
    {
      return avr_out_lpm (insn, xop, plen);
    }

  gcc_assert (2 == GET_MODE_SIZE (GET_MODE (dest)));

  if (REG_P (dest))
    {
      if (REG_P (src)) /* mov r,r */
        {
          if (test_hard_reg_class (STACK_REG, dest))
            {
              if (AVR_HAVE_8BIT_SP)
                return avr_asm_len ("out __SP_L__,%A1", xop, plen, -1);

              if (AVR_XMEGA)
                return avr_asm_len ("out __SP_L__,%A1" CR_TAB
                                    "out __SP_H__,%B1", xop, plen, -2);

              /* Use simple load of SP if no interrupts are  used.  */

              return TARGET_NO_INTERRUPTS
                ? avr_asm_len ("out __SP_H__,%B1" CR_TAB
                               "out __SP_L__,%A1", xop, plen, -2)
                : avr_asm_len ("in __tmp_reg__,__SREG__"  CR_TAB
                               "cli"                      CR_TAB
                               "out __SP_H__,%B1"         CR_TAB
                               "out __SREG__,__tmp_reg__" CR_TAB
                               "out __SP_L__,%A1", xop, plen, -5);
            }
          else if (test_hard_reg_class (STACK_REG, src))
            {
              return !AVR_HAVE_SPH
                ? avr_asm_len ("in %A0,__SP_L__" CR_TAB
                               "clr %B0", xop, plen, -2)

                : avr_asm_len ("in %A0,__SP_L__" CR_TAB
                               "in %B0,__SP_H__", xop, plen, -2);
            }

          return AVR_HAVE_MOVW
            ? avr_asm_len ("movw %0,%1", xop, plen, -1)

            : avr_asm_len ("mov %A0,%A1" CR_TAB
                           "mov %B0,%B1", xop, plen, -2);
        } /* REG_P (src) */
      else if (CONSTANT_P (src))
        {
          return output_reload_inhi (xop, NULL, plen);
        }
      else if (MEM_P (src))
        {
          return out_movhi_r_mr (insn, xop, plen); /* mov r,m */
        }
    }
  else if (MEM_P (dest))
    {
      rtx xop[2];

      xop[0] = dest;
      xop[1] = src == CONST0_RTX (GET_MODE (dest)) ? zero_reg_rtx : src;

      return out_movhi_mr_r (insn, xop, plen);
    }

  fatal_insn ("invalid insn:", insn);

  return "";
}

static const char*
out_movqi_r_mr (rtx insn, rtx op[], int *plen)
{
  rtx dest = op[0];
  rtx src = op[1];
  rtx x = XEXP (src, 0);

  if (CONSTANT_ADDRESS_P (x))
    {
      return optimize > 0 && io_address_operand (x, QImode)
        ? avr_asm_len ("in %0,%i1", op, plen, -1)
        : avr_asm_len ("lds %0,%m1", op, plen, -2);
    }
  else if (GET_CODE (x) == PLUS
           && REG_P (XEXP (x, 0))
           && CONST_INT_P (XEXP (x, 1)))
    {
      /* memory access by reg+disp */

      int disp = INTVAL (XEXP (x, 1));

      if (disp - GET_MODE_SIZE (GET_MODE (src)) >= 63)
        {
          if (REGNO (XEXP (x, 0)) != REG_Y)
            fatal_insn ("incorrect insn:",insn);

          if (disp <= 63 + MAX_LD_OFFSET (GET_MODE (src)))
            return avr_asm_len ("adiw r28,%o1-63" CR_TAB
                                "ldd %0,Y+63"     CR_TAB
                                "sbiw r28,%o1-63", op, plen, -3);

          return avr_asm_len ("subi r28,lo8(-%o1)" CR_TAB
                              "sbci r29,hi8(-%o1)" CR_TAB
                              "ld %0,Y"            CR_TAB
                              "subi r28,lo8(%o1)"  CR_TAB
                              "sbci r29,hi8(%o1)", op, plen, -5);
        }
      else if (REGNO (XEXP (x, 0)) == REG_X)
        {
          /* This is a paranoid case LEGITIMIZE_RELOAD_ADDRESS must exclude
             it but I have this situation with extremal optimizing options.  */

          avr_asm_len ("adiw r26,%o1" CR_TAB
                       "ld %0,X", op, plen, -2);

          if (!reg_overlap_mentioned_p (dest, XEXP (x,0))
              && !reg_unused_after (insn, XEXP (x,0)))
            {
              avr_asm_len ("sbiw r26,%o1", op, plen, 1);
            }

          return "";
        }

      return avr_asm_len ("ldd %0,%1", op, plen, -1);
    }

  return avr_asm_len ("ld %0,%1", op, plen, -1);
}

static const char*
out_movhi_r_mr (rtx insn, rtx op[], int *plen)
{
  rtx dest = op[0];
  rtx src = op[1];
  rtx base = XEXP (src, 0);
  int reg_dest = true_regnum (dest);
  int reg_base = true_regnum (base);
  /* "volatile" forces reading low byte first, even if less efficient,
     for correct operation with 16-bit I/O registers.  */
  int mem_volatile_p = MEM_VOLATILE_P (src);

  if (reg_base > 0)
    {
      if (reg_dest == reg_base)         /* R = (R) */
        return avr_asm_len ("ld __tmp_reg__,%1+" CR_TAB
                            "ld %B0,%1"          CR_TAB
                            "mov %A0,__tmp_reg__", op, plen, -3);

      if (reg_base != REG_X)
        return avr_asm_len ("ld %A0,%1" CR_TAB
                            "ldd %B0,%1+1", op, plen, -2);

      avr_asm_len ("ld %A0,X+" CR_TAB
                   "ld %B0,X", op, plen, -2);

      if (!reg_unused_after (insn, base))
        avr_asm_len ("sbiw r26,1", op, plen, 1);

      return "";
    }
  else if (GET_CODE (base) == PLUS) /* (R + i) */
    {
      int disp = INTVAL (XEXP (base, 1));
      int reg_base = true_regnum (XEXP (base, 0));

      if (disp > MAX_LD_OFFSET (GET_MODE (src)))
        {
          if (REGNO (XEXP (base, 0)) != REG_Y)
            fatal_insn ("incorrect insn:",insn);

          return disp <= 63 + MAX_LD_OFFSET (GET_MODE (src))
            ? avr_asm_len ("adiw r28,%o1-62" CR_TAB
                           "ldd %A0,Y+62"    CR_TAB
                           "ldd %B0,Y+63"    CR_TAB
                           "sbiw r28,%o1-62", op, plen, -4)

            : avr_asm_len ("subi r28,lo8(-%o1)" CR_TAB
                           "sbci r29,hi8(-%o1)" CR_TAB
                           "ld %A0,Y"           CR_TAB
                           "ldd %B0,Y+1"        CR_TAB
                           "subi r28,lo8(%o1)"  CR_TAB
                           "sbci r29,hi8(%o1)", op, plen, -6);
        }

      /* This is a paranoid case. LEGITIMIZE_RELOAD_ADDRESS must exclude
         it but I have this situation with extremal
         optimization options.  */

      if (reg_base == REG_X)
        return reg_base == reg_dest
          ? avr_asm_len ("adiw r26,%o1"      CR_TAB
                         "ld __tmp_reg__,X+" CR_TAB
                         "ld %B0,X"          CR_TAB
                         "mov %A0,__tmp_reg__", op, plen, -4)

          : avr_asm_len ("adiw r26,%o1" CR_TAB
                         "ld %A0,X+"    CR_TAB
                         "ld %B0,X"     CR_TAB
                         "sbiw r26,%o1+1", op, plen, -4);

      return reg_base == reg_dest
        ? avr_asm_len ("ldd __tmp_reg__,%A1" CR_TAB
                       "ldd %B0,%B1"         CR_TAB
                       "mov %A0,__tmp_reg__", op, plen, -3)

        : avr_asm_len ("ldd %A0,%A1" CR_TAB
                       "ldd %B0,%B1", op, plen, -2);
    }
  else if (GET_CODE (base) == PRE_DEC) /* (--R) */
    {
      if (reg_overlap_mentioned_p (dest, XEXP (base, 0)))
        fatal_insn ("incorrect insn:", insn);

      if (!mem_volatile_p)
        return avr_asm_len ("ld %B0,%1" CR_TAB
                            "ld %A0,%1", op, plen, -2);

      return REGNO (XEXP (base, 0)) == REG_X
        ? avr_asm_len ("sbiw r26,2"  CR_TAB
                       "ld %A0,X+"   CR_TAB
                       "ld %B0,X"    CR_TAB
                       "sbiw r26,1", op, plen, -4)

        : avr_asm_len ("sbiw %r1,2"  CR_TAB
                       "ld %A0,%p1"  CR_TAB
                       "ldd %B0,%p1+1", op, plen, -3);
    }
  else if (GET_CODE (base) == POST_INC) /* (R++) */
    {
      if (reg_overlap_mentioned_p (dest, XEXP (base, 0)))
        fatal_insn ("incorrect insn:", insn);

      return avr_asm_len ("ld %A0,%1"  CR_TAB
                          "ld %B0,%1", op, plen, -2);
    }
  else if (CONSTANT_ADDRESS_P (base))
    {
      return optimize > 0 && io_address_operand (base, HImode)
        ? avr_asm_len ("in %A0,%i1" CR_TAB
                       "in %B0,%i1+1", op, plen, -2)

        : avr_asm_len ("lds %A0,%m1" CR_TAB
                       "lds %B0,%m1+1", op, plen, -4);
    }

  fatal_insn ("unknown move insn:",insn);
  return "";
}

static const char*
out_movsi_r_mr (rtx insn, rtx op[], int *l)
{
  rtx dest = op[0];
  rtx src = op[1];
  rtx base = XEXP (src, 0);
  int reg_dest = true_regnum (dest);
  int reg_base = true_regnum (base);
  int tmp;

  if (!l)
    l = &tmp;

  if (reg_base > 0)
    {
      if (reg_base == REG_X)        /* (R26) */
        {
          if (reg_dest == REG_X)
	    /* "ld r26,-X" is undefined */
	    return *l=7, ("adiw r26,3"        CR_TAB
			  "ld r29,X"          CR_TAB
			  "ld r28,-X"         CR_TAB
			  "ld __tmp_reg__,-X" CR_TAB
			  "sbiw r26,1"        CR_TAB
			  "ld r26,X"          CR_TAB
			  "mov r27,__tmp_reg__");
          else if (reg_dest == REG_X - 2)
            return *l=5, ("ld %A0,X+"          CR_TAB
                          "ld %B0,X+"          CR_TAB
                          "ld __tmp_reg__,X+"  CR_TAB
                          "ld %D0,X"           CR_TAB
                          "mov %C0,__tmp_reg__");
          else if (reg_unused_after (insn, base))
            return  *l=4, ("ld %A0,X+"  CR_TAB
                           "ld %B0,X+" CR_TAB
                           "ld %C0,X+" CR_TAB
                           "ld %D0,X");
          else
            return  *l=5, ("ld %A0,X+"  CR_TAB
                           "ld %B0,X+" CR_TAB
                           "ld %C0,X+" CR_TAB
                           "ld %D0,X"  CR_TAB
                           "sbiw r26,3");
        }
      else
        {
          if (reg_dest == reg_base)
            return *l=5, ("ldd %D0,%1+3" CR_TAB
                          "ldd %C0,%1+2" CR_TAB
                          "ldd __tmp_reg__,%1+1"  CR_TAB
                          "ld %A0,%1"  CR_TAB
                          "mov %B0,__tmp_reg__");
          else if (reg_base == reg_dest + 2)
            return *l=5, ("ld %A0,%1"             CR_TAB
                          "ldd %B0,%1+1"          CR_TAB
                          "ldd __tmp_reg__,%1+2"  CR_TAB
                          "ldd %D0,%1+3"          CR_TAB
                          "mov %C0,__tmp_reg__");
          else
            return *l=4, ("ld %A0,%1"    CR_TAB
                          "ldd %B0,%1+1" CR_TAB
                          "ldd %C0,%1+2" CR_TAB
                          "ldd %D0,%1+3");
        }
    }
  else if (GET_CODE (base) == PLUS) /* (R + i) */
    {
      int disp = INTVAL (XEXP (base, 1));

      if (disp > MAX_LD_OFFSET (GET_MODE (src)))
	{
	  if (REGNO (XEXP (base, 0)) != REG_Y)
	    fatal_insn ("incorrect insn:",insn);

	  if (disp <= 63 + MAX_LD_OFFSET (GET_MODE (src)))
	    return *l = 6, ("adiw r28,%o1-60" CR_TAB
			    "ldd %A0,Y+60"    CR_TAB
			    "ldd %B0,Y+61"    CR_TAB
			    "ldd %C0,Y+62"    CR_TAB
			    "ldd %D0,Y+63"    CR_TAB
			    "sbiw r28,%o1-60");

	  return *l = 8, ("subi r28,lo8(-%o1)" CR_TAB
			  "sbci r29,hi8(-%o1)" CR_TAB
			  "ld %A0,Y"           CR_TAB
			  "ldd %B0,Y+1"        CR_TAB
			  "ldd %C0,Y+2"        CR_TAB
			  "ldd %D0,Y+3"        CR_TAB
			  "subi r28,lo8(%o1)"  CR_TAB
			  "sbci r29,hi8(%o1)");
	}

      reg_base = true_regnum (XEXP (base, 0));
      if (reg_base == REG_X)
	{
	  /* R = (X + d) */
	  if (reg_dest == REG_X)
	    {
	      *l = 7;
	      /* "ld r26,-X" is undefined */
	      return ("adiw r26,%o1+3"    CR_TAB
		      "ld r29,X"          CR_TAB
		      "ld r28,-X"         CR_TAB
		      "ld __tmp_reg__,-X" CR_TAB
		      "sbiw r26,1"        CR_TAB
		      "ld r26,X"          CR_TAB
		      "mov r27,__tmp_reg__");
	    }
	  *l = 6;
	  if (reg_dest == REG_X - 2)
	    return ("adiw r26,%o1"      CR_TAB
		    "ld r24,X+"         CR_TAB
		    "ld r25,X+"         CR_TAB
		    "ld __tmp_reg__,X+" CR_TAB
		    "ld r27,X"          CR_TAB
		    "mov r26,__tmp_reg__");

	  return ("adiw r26,%o1" CR_TAB
		  "ld %A0,X+"    CR_TAB
		  "ld %B0,X+"    CR_TAB
		  "ld %C0,X+"    CR_TAB
		  "ld %D0,X"     CR_TAB
		  "sbiw r26,%o1+3");
	}
      if (reg_dest == reg_base)
        return *l=5, ("ldd %D0,%D1"          CR_TAB
                      "ldd %C0,%C1"          CR_TAB
                      "ldd __tmp_reg__,%B1"  CR_TAB
                      "ldd %A0,%A1"          CR_TAB
                      "mov %B0,__tmp_reg__");
      else if (reg_dest == reg_base - 2)
        return *l=5, ("ldd %A0,%A1"          CR_TAB
                      "ldd %B0,%B1"          CR_TAB
                      "ldd __tmp_reg__,%C1"  CR_TAB
                      "ldd %D0,%D1"          CR_TAB
                      "mov %C0,__tmp_reg__");
      return *l=4, ("ldd %A0,%A1" CR_TAB
                    "ldd %B0,%B1" CR_TAB
                    "ldd %C0,%C1" CR_TAB
                    "ldd %D0,%D1");
    }
  else if (GET_CODE (base) == PRE_DEC) /* (--R) */
    return *l=4, ("ld %D0,%1" CR_TAB
		  "ld %C0,%1" CR_TAB
		  "ld %B0,%1" CR_TAB
		  "ld %A0,%1");
  else if (GET_CODE (base) == POST_INC) /* (R++) */
    return *l=4, ("ld %A0,%1" CR_TAB
		  "ld %B0,%1" CR_TAB
		  "ld %C0,%1" CR_TAB
		  "ld %D0,%1");
  else if (CONSTANT_ADDRESS_P (base))
    return *l=8, ("lds %A0,%m1"   CR_TAB
                  "lds %B0,%m1+1" CR_TAB
                  "lds %C0,%m1+2" CR_TAB
                  "lds %D0,%m1+3");

  fatal_insn ("unknown move insn:",insn);
  return "";
}

static const char*
out_movsi_mr_r (rtx insn, rtx op[], int *l)
{
  rtx dest = op[0];
  rtx src = op[1];
  rtx base = XEXP (dest, 0);
  int reg_base = true_regnum (base);
  int reg_src = true_regnum (src);
  int tmp;

  if (!l)
    l = &tmp;

  if (CONSTANT_ADDRESS_P (base))
    return *l=8,("sts %m0,%A1" CR_TAB
                 "sts %m0+1,%B1" CR_TAB
                 "sts %m0+2,%C1" CR_TAB
                 "sts %m0+3,%D1");
  if (reg_base > 0)                 /* (r) */
    {
      if (reg_base == REG_X)                /* (R26) */
        {
          if (reg_src == REG_X)
            {
	      /* "st X+,r26" is undefined */
              if (reg_unused_after (insn, base))
		return *l=6, ("mov __tmp_reg__,r27" CR_TAB
			      "st X,r26"            CR_TAB
			      "adiw r26,1"          CR_TAB
			      "st X+,__tmp_reg__"   CR_TAB
			      "st X+,r28"           CR_TAB
			      "st X,r29");
              else
                return *l=7, ("mov __tmp_reg__,r27" CR_TAB
			      "st X,r26"            CR_TAB
			      "adiw r26,1"          CR_TAB
			      "st X+,__tmp_reg__"   CR_TAB
			      "st X+,r28"           CR_TAB
			      "st X,r29"            CR_TAB
			      "sbiw r26,3");
            }
          else if (reg_base == reg_src + 2)
            {
              if (reg_unused_after (insn, base))
                return *l=7, ("mov __zero_reg__,%C1" CR_TAB
                              "mov __tmp_reg__,%D1"  CR_TAB
                              "st %0+,%A1"           CR_TAB
                              "st %0+,%B1"           CR_TAB
                              "st %0+,__zero_reg__"  CR_TAB
                              "st %0,__tmp_reg__"    CR_TAB
                              "clr __zero_reg__");
              else
                return *l=8, ("mov __zero_reg__,%C1" CR_TAB
                              "mov __tmp_reg__,%D1"  CR_TAB
                              "st %0+,%A1"           CR_TAB
                              "st %0+,%B1"           CR_TAB
                              "st %0+,__zero_reg__"  CR_TAB
                              "st %0,__tmp_reg__"    CR_TAB
                              "clr __zero_reg__"     CR_TAB
                              "sbiw r26,3");
            }
          return *l=5, ("st %0+,%A1" CR_TAB
                        "st %0+,%B1" CR_TAB
                        "st %0+,%C1" CR_TAB
                        "st %0,%D1"  CR_TAB
                        "sbiw r26,3");
        }
      else
        return *l=4, ("st %0,%A1"    CR_TAB
		      "std %0+1,%B1" CR_TAB
		      "std %0+2,%C1" CR_TAB
		      "std %0+3,%D1");
    }
  else if (GET_CODE (base) == PLUS) /* (R + i) */
    {
      int disp = INTVAL (XEXP (base, 1));
      reg_base = REGNO (XEXP (base, 0));
      if (disp > MAX_LD_OFFSET (GET_MODE (dest)))
	{
	  if (reg_base != REG_Y)
	    fatal_insn ("incorrect insn:",insn);

	  if (disp <= 63 + MAX_LD_OFFSET (GET_MODE (dest)))
	    return *l = 6, ("adiw r28,%o0-60" CR_TAB
			    "std Y+60,%A1"    CR_TAB
			    "std Y+61,%B1"    CR_TAB
			    "std Y+62,%C1"    CR_TAB
			    "std Y+63,%D1"    CR_TAB
			    "sbiw r28,%o0-60");

	  return *l = 8, ("subi r28,lo8(-%o0)" CR_TAB
			  "sbci r29,hi8(-%o0)" CR_TAB
			  "st Y,%A1"           CR_TAB
			  "std Y+1,%B1"        CR_TAB
			  "std Y+2,%C1"        CR_TAB
			  "std Y+3,%D1"        CR_TAB
			  "subi r28,lo8(%o0)"  CR_TAB
			  "sbci r29,hi8(%o0)");
	}
      if (reg_base == REG_X)
	{
	  /* (X + d) = R */
	  if (reg_src == REG_X)
	    {
	      *l = 9;
	      return ("mov __tmp_reg__,r26"  CR_TAB
		      "mov __zero_reg__,r27" CR_TAB
		      "adiw r26,%o0"         CR_TAB
		      "st X+,__tmp_reg__"    CR_TAB
		      "st X+,__zero_reg__"   CR_TAB
		      "st X+,r28"            CR_TAB
		      "st X,r29"             CR_TAB
		      "clr __zero_reg__"     CR_TAB
		      "sbiw r26,%o0+3");
	    }
	  else if (reg_src == REG_X - 2)
	    {
	      *l = 9;
	      return ("mov __tmp_reg__,r26"  CR_TAB
		      "mov __zero_reg__,r27" CR_TAB
		      "adiw r26,%o0"         CR_TAB
		      "st X+,r24"            CR_TAB
		      "st X+,r25"            CR_TAB
		      "st X+,__tmp_reg__"    CR_TAB
		      "st X,__zero_reg__"    CR_TAB
		      "clr __zero_reg__"     CR_TAB
		      "sbiw r26,%o0+3");
	    }
	  *l = 6;
	  return ("adiw r26,%o0" CR_TAB
		  "st X+,%A1"    CR_TAB
		  "st X+,%B1"    CR_TAB
		  "st X+,%C1"    CR_TAB
		  "st X,%D1"     CR_TAB
		  "sbiw r26,%o0+3");
	}
      return *l=4, ("std %A0,%A1" CR_TAB
		    "std %B0,%B1" CR_TAB
		    "std %C0,%C1" CR_TAB
		    "std %D0,%D1");
    }
  else if (GET_CODE (base) == PRE_DEC) /* (--R) */
    return *l=4, ("st %0,%D1" CR_TAB
		  "st %0,%C1" CR_TAB
		  "st %0,%B1" CR_TAB
		  "st %0,%A1");
  else if (GET_CODE (base) == POST_INC) /* (R++) */
    return *l=4, ("st %0,%A1" CR_TAB
		  "st %0,%B1" CR_TAB
		  "st %0,%C1" CR_TAB
		  "st %0,%D1");
  fatal_insn ("unknown move insn:",insn);
  return "";
}

const char *
output_movsisf (rtx insn, rtx operands[], int *l)
{
  int dummy;
  rtx dest = operands[0];
  rtx src = operands[1];
  int *real_l = l;

  if (avr_mem_flash_p (src)
      || avr_mem_flash_p (dest))
    {
      return avr_out_lpm (insn, operands, real_l);
    }

  if (!l)
    l = &dummy;

  gcc_assert (4 == GET_MODE_SIZE (GET_MODE (dest)));
  if (REG_P (dest))
    {
      if (REG_P (src)) /* mov r,r */
	{
	  if (true_regnum (dest) > true_regnum (src))
	    {
	      if (AVR_HAVE_MOVW)
		{
		  *l = 2;
		  return ("movw %C0,%C1" CR_TAB
			  "movw %A0,%A1");
		}
	      *l = 4;
	      return ("mov %D0,%D1" CR_TAB
		      "mov %C0,%C1" CR_TAB
		      "mov %B0,%B1" CR_TAB
		      "mov %A0,%A1");
	    }
	  else
	    {
	      if (AVR_HAVE_MOVW)
		{
		  *l = 2;
		  return ("movw %A0,%A1" CR_TAB
			  "movw %C0,%C1");
		}
	      *l = 4;
	      return ("mov %A0,%A1" CR_TAB
		      "mov %B0,%B1" CR_TAB
		      "mov %C0,%C1" CR_TAB
		      "mov %D0,%D1");
	    }
	}
      else if (CONSTANT_P (src))
	{
          return output_reload_insisf (operands, NULL_RTX, real_l);
        }
      else if (MEM_P (src))
	return out_movsi_r_mr (insn, operands, real_l); /* mov r,m */
    }
  else if (MEM_P (dest))
    {
      const char *templ;

      if (src == CONST0_RTX (GET_MODE (dest)))
	  operands[1] = zero_reg_rtx;

      templ = out_movsi_mr_r (insn, operands, real_l);

      if (!real_l)
	output_asm_insn (templ, operands);

      operands[1] = src;
      return "";
    }
  fatal_insn ("invalid insn:", insn);
  return "";
}


/* Handle loads of 24-bit types from memory to register.  */

static const char*
avr_out_load_psi (rtx insn, rtx *op, int *plen)
{
  rtx dest = op[0];
  rtx src = op[1];
  rtx base = XEXP (src, 0);
  int reg_dest = true_regnum (dest);
  int reg_base = true_regnum (base);

  if (reg_base > 0)
    {
      if (reg_base == REG_X)        /* (R26) */
        {
          if (reg_dest == REG_X)
            /* "ld r26,-X" is undefined */
            return avr_asm_len ("adiw r26,2"        CR_TAB
                                "ld r28,X"          CR_TAB
                                "ld __tmp_reg__,-X" CR_TAB
                                "sbiw r26,1"        CR_TAB
                                "ld r26,X"          CR_TAB
                                "mov r27,__tmp_reg__", op, plen, -6);
          else
            {
              avr_asm_len ("ld %A0,X+" CR_TAB
                           "ld %B0,X+" CR_TAB
                           "ld %C0,X", op, plen, -3);

              if (reg_dest != REG_X - 2
                  && !reg_unused_after (insn, base))
                {
                  avr_asm_len ("sbiw r26,2", op, plen, 1);
                }

              return "";
            }
        }
      else /* reg_base != REG_X */
        {
          if (reg_dest == reg_base)
            return avr_asm_len ("ldd %C0,%1+2"          CR_TAB
                                "ldd __tmp_reg__,%1+1"  CR_TAB
                                "ld  %A0,%1"            CR_TAB
                                "mov %B0,__tmp_reg__", op, plen, -4);
          else
            return avr_asm_len ("ld  %A0,%1"    CR_TAB
                                "ldd %B0,%1+1"  CR_TAB
                                "ldd %C0,%1+2", op, plen, -3);
        }
    }
  else if (GET_CODE (base) == PLUS) /* (R + i) */
    {
      int disp = INTVAL (XEXP (base, 1));

      if (disp > MAX_LD_OFFSET (GET_MODE (src)))
        {
          if (REGNO (XEXP (base, 0)) != REG_Y)
            fatal_insn ("incorrect insn:",insn);

          if (disp <= 63 + MAX_LD_OFFSET (GET_MODE (src)))
            return avr_asm_len ("adiw r28,%o1-61" CR_TAB
                                "ldd %A0,Y+61"    CR_TAB
                                "ldd %B0,Y+62"    CR_TAB
                                "ldd %C0,Y+63"    CR_TAB
                                "sbiw r28,%o1-61", op, plen, -5);

          return avr_asm_len ("subi r28,lo8(-%o1)" CR_TAB
                              "sbci r29,hi8(-%o1)" CR_TAB
                              "ld  %A0,Y"           CR_TAB
                              "ldd %B0,Y+1"        CR_TAB
                              "ldd %C0,Y+2"        CR_TAB
                              "subi r28,lo8(%o1)"  CR_TAB
                              "sbci r29,hi8(%o1)", op, plen, -7);
        }

      reg_base = true_regnum (XEXP (base, 0));
      if (reg_base == REG_X)
        {
          /* R = (X + d) */
          if (reg_dest == REG_X)
            {
              /* "ld r26,-X" is undefined */
              return avr_asm_len ("adiw r26,%o1+2"     CR_TAB
                                  "ld  r28,X"          CR_TAB
                                  "ld  __tmp_reg__,-X" CR_TAB
                                  "sbiw r26,1"         CR_TAB
                                  "ld  r26,X"          CR_TAB
                                  "mov r27,__tmp_reg__", op, plen, -6);
            }

          avr_asm_len ("adiw r26,%o1" CR_TAB
                       "ld %A0,X+"    CR_TAB
                       "ld %B0,X+"    CR_TAB
                       "ld %C0,X", op, plen, -4);

          if (reg_dest != REG_W
              && !reg_unused_after (insn, XEXP (base, 0)))
            avr_asm_len ("sbiw r26,%o1+2", op, plen, 1);

          return "";
        }

      if (reg_dest == reg_base)
        return avr_asm_len ("ldd %C0,%C1" CR_TAB
                            "ldd __tmp_reg__,%B1"  CR_TAB
                            "ldd %A0,%A1" CR_TAB
                            "mov %B0,__tmp_reg__", op, plen, -4);

        return avr_asm_len ("ldd %A0,%A1" CR_TAB
                            "ldd %B0,%B1" CR_TAB
                            "ldd %C0,%C1", op, plen, -3);
    }
  else if (GET_CODE (base) == PRE_DEC) /* (--R) */
    return avr_asm_len ("ld %C0,%1" CR_TAB
                        "ld %B0,%1" CR_TAB
                        "ld %A0,%1", op, plen, -3);
  else if (GET_CODE (base) == POST_INC) /* (R++) */
    return avr_asm_len ("ld %A0,%1" CR_TAB
                        "ld %B0,%1" CR_TAB
                        "ld %C0,%1", op, plen, -3);

  else if (CONSTANT_ADDRESS_P (base))
    return avr_asm_len ("lds %A0,%m1" CR_TAB
                        "lds %B0,%m1+1" CR_TAB
                        "lds %C0,%m1+2", op, plen , -6);

  fatal_insn ("unknown move insn:",insn);
  return "";
}

/* Handle store of 24-bit type from register or zero to memory.  */

static const char*
avr_out_store_psi (rtx insn, rtx *op, int *plen)
{
  rtx dest = op[0];
  rtx src = op[1];
  rtx base = XEXP (dest, 0);
  int reg_base = true_regnum (base);

  if (CONSTANT_ADDRESS_P (base))
    return avr_asm_len ("sts %m0,%A1"   CR_TAB
                        "sts %m0+1,%B1" CR_TAB
                        "sts %m0+2,%C1", op, plen, -6);

  if (reg_base > 0)                 /* (r) */
    {
      if (reg_base == REG_X)        /* (R26) */
        {
          gcc_assert (!reg_overlap_mentioned_p (base, src));

          avr_asm_len ("st %0+,%A1"  CR_TAB
                       "st %0+,%B1" CR_TAB
                       "st %0,%C1", op, plen, -3);

          if (!reg_unused_after (insn, base))
            avr_asm_len ("sbiw r26,2", op, plen, 1);

          return "";
        }
      else
        return avr_asm_len ("st %0,%A1"    CR_TAB
                            "std %0+1,%B1" CR_TAB
                            "std %0+2,%C1", op, plen, -3);
    }
  else if (GET_CODE (base) == PLUS) /* (R + i) */
    {
      int disp = INTVAL (XEXP (base, 1));
      reg_base = REGNO (XEXP (base, 0));

      if (disp > MAX_LD_OFFSET (GET_MODE (dest)))
        {
          if (reg_base != REG_Y)
            fatal_insn ("incorrect insn:",insn);

          if (disp <= 63 + MAX_LD_OFFSET (GET_MODE (dest)))
            return avr_asm_len ("adiw r28,%o0-61" CR_TAB
                                "std Y+61,%A1"    CR_TAB
                                "std Y+62,%B1"    CR_TAB
                                "std Y+63,%C1"    CR_TAB
                                "sbiw r28,%o0-61", op, plen, -5);

          return avr_asm_len ("subi r28,lo8(-%o0)" CR_TAB
                              "sbci r29,hi8(-%o0)" CR_TAB
                              "st Y,%A1"           CR_TAB
                              "std Y+1,%B1"        CR_TAB
                              "std Y+2,%C1"        CR_TAB
                              "subi r28,lo8(%o0)"  CR_TAB
                              "sbci r29,hi8(%o0)", op, plen, -7);
        }
      if (reg_base == REG_X)
        {
          /* (X + d) = R */
          gcc_assert (!reg_overlap_mentioned_p (XEXP (base, 0), src));

          avr_asm_len ("adiw r26,%o0" CR_TAB
                       "st X+,%A1"    CR_TAB
                       "st X+,%B1"    CR_TAB
                       "st X,%C1", op, plen, -4);

          if (!reg_unused_after (insn, XEXP (base, 0)))
            avr_asm_len ("sbiw r26,%o0+2", op, plen, 1);

          return "";
        }

      return avr_asm_len ("std %A0,%A1" CR_TAB
                          "std %B0,%B1" CR_TAB
                          "std %C0,%C1", op, plen, -3);
    }
  else if (GET_CODE (base) == PRE_DEC) /* (--R) */
    return avr_asm_len ("st %0,%C1" CR_TAB
                        "st %0,%B1" CR_TAB
                        "st %0,%A1", op, plen, -3);
  else if (GET_CODE (base) == POST_INC) /* (R++) */
    return avr_asm_len ("st %0,%A1" CR_TAB
                        "st %0,%B1" CR_TAB
                        "st %0,%C1", op, plen, -3);

  fatal_insn ("unknown move insn:",insn);
  return "";
}


/* Move around 24-bit stuff.  */

const char *
avr_out_movpsi (rtx insn, rtx *op, int *plen)
{
  rtx dest = op[0];
  rtx src = op[1];

  if (avr_mem_flash_p (src)
      || avr_mem_flash_p (dest))
    {
      return avr_out_lpm (insn, op, plen);
    }

  if (register_operand (dest, VOIDmode))
    {
      if (register_operand (src, VOIDmode)) /* mov r,r */
        {
          if (true_regnum (dest) > true_regnum (src))
            {
              avr_asm_len ("mov %C0,%C1", op, plen, -1);

              if (AVR_HAVE_MOVW)
                return avr_asm_len ("movw %A0,%A1", op, plen, 1);
              else
                return avr_asm_len ("mov %B0,%B1"  CR_TAB
                                    "mov %A0,%A1", op, plen, 2);
            }
          else
            {
              if (AVR_HAVE_MOVW)
                avr_asm_len ("movw %A0,%A1", op, plen, -1);
              else
                avr_asm_len ("mov %A0,%A1"  CR_TAB
                             "mov %B0,%B1", op, plen, -2);

              return avr_asm_len ("mov %C0,%C1", op, plen, 1);
            }
        }
      else if (CONSTANT_P (src))
        {
          return avr_out_reload_inpsi (op, NULL_RTX, plen);
        }
      else if (MEM_P (src))
        return avr_out_load_psi (insn, op, plen); /* mov r,m */
    }
  else if (MEM_P (dest))
    {
      rtx xop[2];

      xop[0] = dest;
      xop[1] = src == CONST0_RTX (GET_MODE (dest)) ? zero_reg_rtx : src;

      return avr_out_store_psi (insn, xop, plen);
    }

  fatal_insn ("invalid insn:", insn);
  return "";
}


static const char*
out_movqi_mr_r (rtx insn, rtx op[], int *plen)
{
  rtx dest = op[0];
  rtx src = op[1];
  rtx x = XEXP (dest, 0);

  if (CONSTANT_ADDRESS_P (x))
    {
      return optimize > 0 && io_address_operand (x, QImode)
        ? avr_asm_len ("out %i0,%1", op, plen, -1)
        : avr_asm_len ("sts %m0,%1", op, plen, -2);
    }
  else if (GET_CODE (x) == PLUS
           && REG_P (XEXP (x, 0))
           && CONST_INT_P (XEXP (x, 1)))
    {
      /* memory access by reg+disp */

      int disp = INTVAL (XEXP (x, 1));

      if (disp - GET_MODE_SIZE (GET_MODE (dest)) >= 63)
        {
          if (REGNO (XEXP (x, 0)) != REG_Y)
            fatal_insn ("incorrect insn:",insn);

          if (disp <= 63 + MAX_LD_OFFSET (GET_MODE (dest)))
            return avr_asm_len ("adiw r28,%o0-63" CR_TAB
                                "std Y+63,%1"     CR_TAB
                                "sbiw r28,%o0-63", op, plen, -3);

          return avr_asm_len ("subi r28,lo8(-%o0)" CR_TAB
                              "sbci r29,hi8(-%o0)" CR_TAB
                              "st Y,%1"            CR_TAB
                              "subi r28,lo8(%o0)"  CR_TAB
                              "sbci r29,hi8(%o0)", op, plen, -5);
        }
      else if (REGNO (XEXP (x,0)) == REG_X)
        {
          if (reg_overlap_mentioned_p (src, XEXP (x, 0)))
            {
              avr_asm_len ("mov __tmp_reg__,%1" CR_TAB
                           "adiw r26,%o0"       CR_TAB
                           "st X,__tmp_reg__", op, plen, -3);
            }
          else
            {
              avr_asm_len ("adiw r26,%o0" CR_TAB
                           "st X,%1", op, plen, -2);
            }

          if (!reg_unused_after (insn, XEXP (x,0)))
            avr_asm_len ("sbiw r26,%o0", op, plen, 1);

          return "";
        }

      return avr_asm_len ("std %0,%1", op, plen, -1);
    }

  return avr_asm_len ("st %0,%1", op, plen, -1);
}


/* Helper for the next function for XMEGA.  It does the same
   but with low byte first.  */

static const char*
avr_out_movhi_mr_r_xmega (rtx insn, rtx op[], int *plen)
{
  rtx dest = op[0];
  rtx src = op[1];
  rtx base = XEXP (dest, 0);
  int reg_base = true_regnum (base);
  int reg_src = true_regnum (src);

  /* "volatile" forces writing low byte first, even if less efficient,
     for correct operation with 16-bit I/O registers like SP.  */
  int mem_volatile_p = MEM_VOLATILE_P (dest);

  if (CONSTANT_ADDRESS_P (base))
    return optimize > 0 && io_address_operand (base, HImode)
      ? avr_asm_len ("out %i0,%A1" CR_TAB
                     "out %i0+1,%B1", op, plen, -2)

      : avr_asm_len ("sts %m0,%A1" CR_TAB
                     "sts %m0+1,%B1", op, plen, -4);

  if (reg_base > 0)
    {
      if (reg_base != REG_X)
        return avr_asm_len ("st %0,%A1" CR_TAB
                            "std %0+1,%B1", op, plen, -2);

      if (reg_src == REG_X)
        /* "st X+,r26" and "st -X,r26" are undefined.  */
        avr_asm_len ("mov __tmp_reg__,r27" CR_TAB
                     "st X,r26"            CR_TAB
                     "adiw r26,1"          CR_TAB
                     "st X,__tmp_reg__", op, plen, -4);
      else
        avr_asm_len ("st X+,%A1" CR_TAB
                     "st X,%B1", op, plen, -2);

      return reg_unused_after (insn, base)
        ? ""
        : avr_asm_len ("sbiw r26,1", op, plen, 1);
    }
  else if (GET_CODE (base) == PLUS)
    {
      int disp = INTVAL (XEXP (base, 1));
      reg_base = REGNO (XEXP (base, 0));
      if (disp > MAX_LD_OFFSET (GET_MODE (dest)))
        {
          if (reg_base != REG_Y)
            fatal_insn ("incorrect insn:",insn);

          return disp <= 63 + MAX_LD_OFFSET (GET_MODE (dest))
            ? avr_asm_len ("adiw r28,%o0-62" CR_TAB
                           "std Y+62,%A1"    CR_TAB
                           "std Y+63,%B1"    CR_TAB
                           "sbiw r28,%o0-62", op, plen, -4)

            : avr_asm_len ("subi r28,lo8(-%o0)" CR_TAB
                           "sbci r29,hi8(-%o0)" CR_TAB
                           "st Y,%A1"           CR_TAB
                           "std Y+1,%B1"        CR_TAB
                           "subi r28,lo8(%o0)"  CR_TAB
                           "sbci r29,hi8(%o0)", op, plen, -6);
        }

      if (reg_base != REG_X)
        return avr_asm_len ("std %A0,%A1" CR_TAB
                            "std %B0,%B1", op, plen, -2);
      /* (X + d) = R */
      return reg_src == REG_X
        ? avr_asm_len ("mov __tmp_reg__,r26"  CR_TAB
                       "mov __zero_reg__,r27" CR_TAB
                       "adiw r26,%o0"         CR_TAB
                       "st X+,__tmp_reg__"    CR_TAB
                       "st X,__zero_reg__"    CR_TAB
                       "clr __zero_reg__"     CR_TAB
                       "sbiw r26,%o0+1", op, plen, -7)

        : avr_asm_len ("adiw r26,%o0" CR_TAB
                       "st X+,%A1"    CR_TAB
                       "st X,%B1"     CR_TAB
                       "sbiw r26,%o0+1", op, plen, -4);
    }
  else if (GET_CODE (base) == PRE_DEC) /* (--R) */
    {
      if (!mem_volatile_p)
        return avr_asm_len ("st %0,%B1" CR_TAB
                            "st %0,%A1", op, plen, -2);

      return REGNO (XEXP (base, 0)) == REG_X
        ? avr_asm_len ("sbiw r26,2"  CR_TAB
                       "st X+,%A1"   CR_TAB
                       "st X,%B1"    CR_TAB
                       "sbiw r26,1", op, plen, -4)

        : avr_asm_len ("sbiw %r0,2"  CR_TAB
                       "st %p0,%A1"  CR_TAB
                       "std %p0+1,%B1", op, plen, -3);
    }
  else if (GET_CODE (base) == POST_INC) /* (R++) */
    {
      return avr_asm_len ("st %0,%A1"  CR_TAB
                          "st %0,%B1", op, plen, -2);

    }
  fatal_insn ("unknown move insn:",insn);
  return "";
}


static const char*
out_movhi_mr_r (rtx insn, rtx op[], int *plen)
{
  rtx dest = op[0];
  rtx src = op[1];
  rtx base = XEXP (dest, 0);
  int reg_base = true_regnum (base);
  int reg_src = true_regnum (src);
  int mem_volatile_p;

  /* "volatile" forces writing high-byte first (no-xmega) resp.
     low-byte first (xmega) even if less efficient, for correct
     operation with 16-bit I/O registers like.  */

  if (AVR_XMEGA)
    return avr_out_movhi_mr_r_xmega (insn, op, plen);

  mem_volatile_p = MEM_VOLATILE_P (dest);

  if (CONSTANT_ADDRESS_P (base))
    return optimize > 0 && io_address_operand (base, HImode)
      ? avr_asm_len ("out %i0+1,%B1" CR_TAB
                     "out %i0,%A1", op, plen, -2)

      : avr_asm_len ("sts %m0+1,%B1" CR_TAB
                     "sts %m0,%A1", op, plen, -4);

  if (reg_base > 0)
    {
      if (reg_base != REG_X)
        return avr_asm_len ("std %0+1,%B1" CR_TAB
                            "st %0,%A1", op, plen, -2);

      if (reg_src == REG_X)
        /* "st X+,r26" and "st -X,r26" are undefined.  */
        return !mem_volatile_p && reg_unused_after (insn, src)
          ? avr_asm_len ("mov __tmp_reg__,r27" CR_TAB
                         "st X,r26"            CR_TAB
                         "adiw r26,1"          CR_TAB
                         "st X,__tmp_reg__", op, plen, -4)

          : avr_asm_len ("mov __tmp_reg__,r27" CR_TAB
                         "adiw r26,1"          CR_TAB
                         "st X,__tmp_reg__"    CR_TAB
                         "sbiw r26,1"          CR_TAB
                         "st X,r26", op, plen, -5);

      return !mem_volatile_p && reg_unused_after (insn, base)
        ? avr_asm_len ("st X+,%A1" CR_TAB
                       "st X,%B1", op, plen, -2)
        : avr_asm_len ("adiw r26,1" CR_TAB
                       "st X,%B1"   CR_TAB
                       "st -X,%A1", op, plen, -3);
    }
  else if (GET_CODE (base) == PLUS)
    {
      int disp = INTVAL (XEXP (base, 1));
      reg_base = REGNO (XEXP (base, 0));
      if (disp > MAX_LD_OFFSET (GET_MODE (dest)))
        {
          if (reg_base != REG_Y)
            fatal_insn ("incorrect insn:",insn);

          return disp <= 63 + MAX_LD_OFFSET (GET_MODE (dest))
            ? avr_asm_len ("adiw r28,%o0-62" CR_TAB
                           "std Y+63,%B1"    CR_TAB
                           "std Y+62,%A1"    CR_TAB
                           "sbiw r28,%o0-62", op, plen, -4)

            : avr_asm_len ("subi r28,lo8(-%o0)" CR_TAB
                           "sbci r29,hi8(-%o0)" CR_TAB
                           "std Y+1,%B1"        CR_TAB
                           "st Y,%A1"           CR_TAB
                           "subi r28,lo8(%o0)"  CR_TAB
                           "sbci r29,hi8(%o0)", op, plen, -6);
        }

      if (reg_base != REG_X)
        return avr_asm_len ("std %B0,%B1" CR_TAB
                            "std %A0,%A1", op, plen, -2);
      /* (X + d) = R */
      return reg_src == REG_X
        ? avr_asm_len ("mov __tmp_reg__,r26"  CR_TAB
                       "mov __zero_reg__,r27" CR_TAB
                       "adiw r26,%o0+1"       CR_TAB
                       "st X,__zero_reg__"    CR_TAB
                       "st -X,__tmp_reg__"    CR_TAB
                       "clr __zero_reg__"     CR_TAB
                       "sbiw r26,%o0", op, plen, -7)

        : avr_asm_len ("adiw r26,%o0+1" CR_TAB
                       "st X,%B1"       CR_TAB
                       "st -X,%A1"      CR_TAB
                       "sbiw r26,%o0", op, plen, -4);
    }
  else if (GET_CODE (base) == PRE_DEC) /* (--R) */
    {
      return avr_asm_len ("st %0,%B1" CR_TAB
                          "st %0,%A1", op, plen, -2);
    }
  else if (GET_CODE (base) == POST_INC) /* (R++) */
    {
      if (!mem_volatile_p)
        return avr_asm_len ("st %0,%A1"  CR_TAB
                            "st %0,%B1", op, plen, -2);

      return REGNO (XEXP (base, 0)) == REG_X
        ? avr_asm_len ("adiw r26,1"  CR_TAB
                       "st X,%B1"    CR_TAB
                       "st -X,%A1"   CR_TAB
                       "adiw r26,2", op, plen, -4)

        : avr_asm_len ("std %p0+1,%B1" CR_TAB
                       "st %p0,%A1"    CR_TAB
                       "adiw %r0,2", op, plen, -3);
    }
  fatal_insn ("unknown move insn:",insn);
  return "";
}

/* Return 1 if frame pointer for current function required.  */

static bool
avr_frame_pointer_required_p (void)
{
  return (cfun->calls_alloca
          || cfun->calls_setjmp
          || cfun->has_nonlocal_label
          || crtl->args.info.nregs == 0
          || get_frame_size () > 0);
}

/* Returns the condition of compare insn INSN, or UNKNOWN.  */

static RTX_CODE
compare_condition (rtx insn)
{
  rtx next = next_real_insn (insn);

  if (next && JUMP_P (next))
    {
      rtx pat = PATTERN (next);
      rtx src = SET_SRC (pat);

      if (IF_THEN_ELSE == GET_CODE (src))
        return GET_CODE (XEXP (src, 0));
    }

  return UNKNOWN;
}


/* Returns true iff INSN is a tst insn that only tests the sign.  */

static bool
compare_sign_p (rtx insn)
{
  RTX_CODE cond = compare_condition (insn);
  return (cond == GE || cond == LT);
}


/* Returns true iff the next insn is a JUMP_INSN with a condition
   that needs to be swapped (GT, GTU, LE, LEU).  */

static bool
compare_diff_p (rtx insn)
{
  RTX_CODE cond = compare_condition (insn);
  return (cond == GT || cond == GTU || cond == LE || cond == LEU) ? cond : 0;
}

/* Returns true iff INSN is a compare insn with the EQ or NE condition.  */

static bool
compare_eq_p (rtx insn)
{
  RTX_CODE cond = compare_condition (insn);
  return (cond == EQ || cond == NE);
}


/* Output compare instruction

      compare (XOP[0], XOP[1])

   for a register XOP[0] and a compile-time constant XOP[1].  Return "".
   XOP[2] is an 8-bit scratch register as needed.

   PLEN == NULL:  Output instructions.
   PLEN != NULL:  Set *PLEN to the length (in words) of the sequence.
                  Don't output anything.  */

const char*
avr_out_compare (rtx insn, rtx *xop, int *plen)
{
  /* Register to compare and value to compare against. */
  rtx xreg = xop[0];
  rtx xval = xop[1];

  /* MODE of the comparison.  */
  enum machine_mode mode;

  /* Number of bytes to operate on.  */
  int i, n_bytes = GET_MODE_SIZE (GET_MODE (xreg));

  /* Value (0..0xff) held in clobber register xop[2] or -1 if unknown.  */
  int clobber_val = -1;

  /* Map fixed mode operands to integer operands with the same binary
     representation.  They are easier to handle in the remainder.  */

  if (CONST_FIXED_P (xval))
    {
      xreg = avr_to_int_mode (xop[0]);
      xval = avr_to_int_mode (xop[1]);
    }

  mode = GET_MODE (xreg);

  gcc_assert (REG_P (xreg));
  gcc_assert ((CONST_INT_P (xval) && n_bytes <= 4)
              || (const_double_operand (xval, VOIDmode) && n_bytes == 8));

  if (plen)
    *plen = 0;

  /* Comparisons == +/-1 and != +/-1 can be done similar to camparing
     against 0 by ORing the bytes.  This is one instruction shorter.
     Notice that 64-bit comparisons are always against reg:ALL8 18 (ACC_A)
     and therefore don't use this.  */

  if (!test_hard_reg_class (LD_REGS, xreg)
      && compare_eq_p (insn)
      && reg_unused_after (insn, xreg))
    {
      if (xval == const1_rtx)
        {
          avr_asm_len ("dec %A0" CR_TAB
                       "or %A0,%B0", xop, plen, 2);

          if (n_bytes >= 3)
            avr_asm_len ("or %A0,%C0", xop, plen, 1);

          if (n_bytes >= 4)
            avr_asm_len ("or %A0,%D0", xop, plen, 1);

          return "";
        }
      else if (xval == constm1_rtx)
        {
          if (n_bytes >= 4)
            avr_asm_len ("and %A0,%D0", xop, plen, 1);

          if (n_bytes >= 3)
            avr_asm_len ("and %A0,%C0", xop, plen, 1);

          return avr_asm_len ("and %A0,%B0" CR_TAB
                              "com %A0", xop, plen, 2);
        }
    }

  for (i = 0; i < n_bytes; i++)
    {
      /* We compare byte-wise.  */
      rtx reg8 = simplify_gen_subreg (QImode, xreg, mode, i);
      rtx xval8 = simplify_gen_subreg (QImode, xval, mode, i);

      /* 8-bit value to compare with this byte.  */
      unsigned int val8 = UINTVAL (xval8) & GET_MODE_MASK (QImode);

      /* Registers R16..R31 can operate with immediate.  */
      bool ld_reg_p = test_hard_reg_class (LD_REGS, reg8);

      xop[0] = reg8;
      xop[1] = gen_int_mode (val8, QImode);

      /* Word registers >= R24 can use SBIW/ADIW with 0..63.  */

      if (i == 0
          && test_hard_reg_class (ADDW_REGS, reg8))
        {
          int val16 = trunc_int_for_mode (INTVAL (xval), HImode);

          if (IN_RANGE (val16, 0, 63)
              && (val8 == 0
                  || reg_unused_after (insn, xreg)))
            {
              avr_asm_len ("sbiw %0,%1", xop, plen, 1);
              i++;
              continue;
            }

          if (n_bytes == 2
              && IN_RANGE (val16, -63, -1)
              && compare_eq_p (insn)
              && reg_unused_after (insn, xreg))
            {
              return avr_asm_len ("adiw %0,%n1", xop, plen, 1);
            }
        }

      /* Comparing against 0 is easy.  */

      if (val8 == 0)
        {
          avr_asm_len (i == 0
                       ? "cp %0,__zero_reg__"
                       : "cpc %0,__zero_reg__", xop, plen, 1);
          continue;
        }

      /* Upper registers can compare and subtract-with-carry immediates.
         Notice that compare instructions do the same as respective subtract
         instruction; the only difference is that comparisons don't write
         the result back to the target register.  */

      if (ld_reg_p)
        {
          if (i == 0)
            {
              avr_asm_len ("cpi %0,%1", xop, plen, 1);
              continue;
            }
          else if (reg_unused_after (insn, xreg))
            {
              avr_asm_len ("sbci %0,%1", xop, plen, 1);
              continue;
            }
        }

      /* Must load the value into the scratch register.  */

      gcc_assert (REG_P (xop[2]));

      if (clobber_val != (int) val8)
        avr_asm_len ("ldi %2,%1", xop, plen, 1);
      clobber_val = (int) val8;

      avr_asm_len (i == 0
                   ? "cp %0,%2"
                   : "cpc %0,%2", xop, plen, 1);
    }

  return "";
}


/* Prepare operands of compare_const_di2 to be used with avr_out_compare.  */

const char*
avr_out_compare64 (rtx insn, rtx *op, int *plen)
{
  rtx xop[3];

  xop[0] = gen_rtx_REG (DImode, 18);
  xop[1] = op[0];
  xop[2] = op[1];

  return avr_out_compare (insn, xop, plen);
}

/* Output test instruction for HImode.  */

const char*
avr_out_tsthi (rtx insn, rtx *op, int *plen)
{
  if (compare_sign_p (insn))
    {
      avr_asm_len ("tst %B0", op, plen, -1);
    }
  else if (reg_unused_after (insn, op[0])
           && compare_eq_p (insn))
    {
      /* Faster than sbiw if we can clobber the operand.  */
      avr_asm_len ("or %A0,%B0", op, plen, -1);
    }
  else
    {
      avr_out_compare (insn, op, plen);
    }

  return "";
}


/* Output test instruction for PSImode.  */

const char*
avr_out_tstpsi (rtx insn, rtx *op, int *plen)
{
  if (compare_sign_p (insn))
    {
      avr_asm_len ("tst %C0", op, plen, -1);
    }
  else if (reg_unused_after (insn, op[0])
           && compare_eq_p (insn))
    {
      /* Faster than sbiw if we can clobber the operand.  */
      avr_asm_len ("or %A0,%B0" CR_TAB
                   "or %A0,%C0", op, plen, -2);
    }
  else
    {
      avr_out_compare (insn, op, plen);
    }

  return "";
}


/* Output test instruction for SImode.  */

const char*
avr_out_tstsi (rtx insn, rtx *op, int *plen)
{
  if (compare_sign_p (insn))
    {
      avr_asm_len ("tst %D0", op, plen, -1);
    }
  else if (reg_unused_after (insn, op[0])
           && compare_eq_p (insn))
    {
      /* Faster than sbiw if we can clobber the operand.  */
      avr_asm_len ("or %A0,%B0" CR_TAB
                   "or %A0,%C0" CR_TAB
                   "or %A0,%D0", op, plen, -3);
    }
  else
    {
      avr_out_compare (insn, op, plen);
    }

  return "";
}


/* Generate asm equivalent for various shifts.  This only handles cases
   that are not already carefully hand-optimized in ?sh??i3_out.

   OPERANDS[0] resp. %0 in TEMPL is the operand to be shifted.
   OPERANDS[2] is the shift count as CONST_INT, MEM or REG.
   OPERANDS[3] is a QImode scratch register from LD regs if
               available and SCRATCH, otherwise (no scratch available)

   TEMPL is an assembler template that shifts by one position.
   T_LEN is the length of this template.  */

void
out_shift_with_cnt (const char *templ, rtx insn, rtx operands[],
		    int *plen, int t_len)
{
  bool second_label = true;
  bool saved_in_tmp = false;
  bool use_zero_reg = false;
  rtx op[5];

  op[0] = operands[0];
  op[1] = operands[1];
  op[2] = operands[2];
  op[3] = operands[3];

  if (plen)
    *plen = 0;

  if (CONST_INT_P (operands[2]))
    {
      bool scratch = (GET_CODE (PATTERN (insn)) == PARALLEL
                      && REG_P (operands[3]));
      int count = INTVAL (operands[2]);
      int max_len = 10;  /* If larger than this, always use a loop.  */

      if (count <= 0)
          return;

      if (count < 8 && !scratch)
        use_zero_reg = true;

      if (optimize_size)
        max_len = t_len + (scratch ? 3 : (use_zero_reg ? 4 : 5));

      if (t_len * count <= max_len)
        {
          /* Output shifts inline with no loop - faster.  */

          while (count-- > 0)
            avr_asm_len (templ, op, plen, t_len);

          return;
        }

      if (scratch)
        {
          avr_asm_len ("ldi %3,%2", op, plen, 1);
        }
      else if (use_zero_reg)
        {
          /* Hack to save one word: use __zero_reg__ as loop counter.
             Set one bit, then shift in a loop until it is 0 again.  */

          op[3] = zero_reg_rtx;

          avr_asm_len ("set" CR_TAB
                       "bld %3,%2-1", op, plen, 2);
        }
      else
        {
          /* No scratch register available, use one from LD_REGS (saved in
             __tmp_reg__) that doesn't overlap with registers to shift.  */

          op[3] = all_regs_rtx[((REGNO (op[0]) - 1) & 15) + 16];
          op[4] = tmp_reg_rtx;
          saved_in_tmp = true;

          avr_asm_len ("mov %4,%3" CR_TAB
                       "ldi %3,%2", op, plen, 2);
        }

      second_label = false;
    }
  else if (MEM_P (op[2]))
    {
      rtx op_mov[2];

      op_mov[0] = op[3] = tmp_reg_rtx;
      op_mov[1] = op[2];

      out_movqi_r_mr (insn, op_mov, plen);
    }
  else if (register_operand (op[2], QImode))
    {
      op[3] = op[2];

      if (!reg_unused_after (insn, op[2])
          || reg_overlap_mentioned_p (op[0], op[2]))
        {
          op[3] = tmp_reg_rtx;
          avr_asm_len ("mov %3,%2", op, plen, 1);
        }
    }
  else
    fatal_insn ("bad shift insn:", insn);

  if (second_label)
      avr_asm_len ("rjmp 2f", op, plen, 1);

  avr_asm_len ("1:", op, plen, 0);
  avr_asm_len (templ, op, plen, t_len);

  if (second_label)
    avr_asm_len ("2:", op, plen, 0);

  avr_asm_len (use_zero_reg ? "lsr %3" : "dec %3", op, plen, 1);
  avr_asm_len (second_label ? "brpl 1b" : "brne 1b", op, plen, 1);

  if (saved_in_tmp)
    avr_asm_len ("mov %3,%4", op, plen, 1);
}


/* 8bit shift left ((char)x << i)   */

const char *
ashlqi3_out (rtx insn, rtx operands[], int *len)
{
  if (GET_CODE (operands[2]) == CONST_INT)
    {
      int k;

      if (!len)
	len = &k;

      switch (INTVAL (operands[2]))
	{
	default:
	  if (INTVAL (operands[2]) < 8)
	    break;

	  *len = 1;
	  return "clr %0";

	case 1:
	  *len = 1;
	  return "lsl %0";

	case 2:
	  *len = 2;
	  return ("lsl %0" CR_TAB
		  "lsl %0");

	case 3:
	  *len = 3;
	  return ("lsl %0" CR_TAB
		  "lsl %0" CR_TAB
		  "lsl %0");

	case 4:
	  if (test_hard_reg_class (LD_REGS, operands[0]))
	    {
	      *len = 2;
	      return ("swap %0" CR_TAB
		      "andi %0,0xf0");
	    }
	  *len = 4;
	  return ("lsl %0" CR_TAB
		  "lsl %0" CR_TAB
		  "lsl %0" CR_TAB
		  "lsl %0");

	case 5:
	  if (test_hard_reg_class (LD_REGS, operands[0]))
	    {
	      *len = 3;
	      return ("swap %0" CR_TAB
		      "lsl %0"  CR_TAB
		      "andi %0,0xe0");
	    }
	  *len = 5;
	  return ("lsl %0" CR_TAB
		  "lsl %0" CR_TAB
		  "lsl %0" CR_TAB
		  "lsl %0" CR_TAB
		  "lsl %0");

	case 6:
	  if (test_hard_reg_class (LD_REGS, operands[0]))
	    {
	      *len = 4;
	      return ("swap %0" CR_TAB
		      "lsl %0"  CR_TAB
		      "lsl %0"  CR_TAB
		      "andi %0,0xc0");
	    }
	  *len = 6;
	  return ("lsl %0" CR_TAB
		  "lsl %0" CR_TAB
		  "lsl %0" CR_TAB
		  "lsl %0" CR_TAB
		  "lsl %0" CR_TAB
		  "lsl %0");

	case 7:
	  *len = 3;
	  return ("ror %0" CR_TAB
		  "clr %0" CR_TAB
		  "ror %0");
	}
    }
  else if (CONSTANT_P (operands[2]))
    fatal_insn ("internal compiler error.  Incorrect shift:", insn);

  out_shift_with_cnt ("lsl %0",
                      insn, operands, len, 1);
  return "";
}


/* 16bit shift left ((short)x << i)   */

const char *
ashlhi3_out (rtx insn, rtx operands[], int *len)
{
  if (GET_CODE (operands[2]) == CONST_INT)
    {
      int scratch = (GET_CODE (PATTERN (insn)) == PARALLEL);
      int ldi_ok = test_hard_reg_class (LD_REGS, operands[0]);
      int k;
      int *t = len;

      if (!len)
	len = &k;

      switch (INTVAL (operands[2]))
	{
	default:
	  if (INTVAL (operands[2]) < 16)
	    break;

	  *len = 2;
	  return ("clr %B0" CR_TAB
		  "clr %A0");

	case 4:
	  if (optimize_size && scratch)
	    break;  /* 5 */
	  if (ldi_ok)
	    {
	      *len = 6;
	      return ("swap %A0"      CR_TAB
		      "swap %B0"      CR_TAB
		      "andi %B0,0xf0" CR_TAB
		      "eor %B0,%A0"   CR_TAB
		      "andi %A0,0xf0" CR_TAB
		      "eor %B0,%A0");
	    }
	  if (scratch)
	    {
	      *len = 7;
	      return ("swap %A0"    CR_TAB
		      "swap %B0"    CR_TAB
		      "ldi %3,0xf0" CR_TAB
		      "and %B0,%3"      CR_TAB
		      "eor %B0,%A0" CR_TAB
		      "and %A0,%3"      CR_TAB
		      "eor %B0,%A0");
	    }
	  break;  /* optimize_size ? 6 : 8 */

	case 5:
	  if (optimize_size)
	    break;  /* scratch ? 5 : 6 */
	  if (ldi_ok)
	    {
	      *len = 8;
	      return ("lsl %A0"       CR_TAB
		      "rol %B0"       CR_TAB
		      "swap %A0"      CR_TAB
		      "swap %B0"      CR_TAB
		      "andi %B0,0xf0" CR_TAB
		      "eor %B0,%A0"   CR_TAB
		      "andi %A0,0xf0" CR_TAB
		      "eor %B0,%A0");
	    }
	  if (scratch)
	    {
	      *len = 9;
	      return ("lsl %A0"     CR_TAB
		      "rol %B0"     CR_TAB
		      "swap %A0"    CR_TAB
		      "swap %B0"    CR_TAB
		      "ldi %3,0xf0" CR_TAB
		      "and %B0,%3"      CR_TAB
		      "eor %B0,%A0" CR_TAB
		      "and %A0,%3"      CR_TAB
		      "eor %B0,%A0");
	    }
	  break;  /* 10 */

	case 6:
	  if (optimize_size)
	    break;  /* scratch ? 5 : 6 */
	  *len = 9;
	  return ("clr __tmp_reg__" CR_TAB
		  "lsr %B0"         CR_TAB
		  "ror %A0"         CR_TAB
		  "ror __tmp_reg__" CR_TAB
		  "lsr %B0"         CR_TAB
		  "ror %A0"         CR_TAB
		  "ror __tmp_reg__" CR_TAB
		  "mov %B0,%A0"     CR_TAB
		  "mov %A0,__tmp_reg__");

	case 7:
	  *len = 5;
	  return ("lsr %B0"     CR_TAB
		  "mov %B0,%A0" CR_TAB
		  "clr %A0"     CR_TAB
		  "ror %B0"     CR_TAB
		  "ror %A0");

	case 8:
	  return *len = 2, ("mov %B0,%A1" CR_TAB
			    "clr %A0");

	case 9:
	  *len = 3;
	  return ("mov %B0,%A0" CR_TAB
		  "clr %A0"     CR_TAB
		  "lsl %B0");

	case 10:
	  *len = 4;
	  return ("mov %B0,%A0" CR_TAB
		  "clr %A0"     CR_TAB
		  "lsl %B0"     CR_TAB
		  "lsl %B0");

	case 11:
	  *len = 5;
	  return ("mov %B0,%A0" CR_TAB
		  "clr %A0"     CR_TAB
		  "lsl %B0"     CR_TAB
		  "lsl %B0"     CR_TAB
		  "lsl %B0");

	case 12:
	  if (ldi_ok)
	    {
	      *len = 4;
	      return ("mov %B0,%A0" CR_TAB
		      "clr %A0"     CR_TAB
		      "swap %B0"    CR_TAB
		      "andi %B0,0xf0");
	    }
	  if (scratch)
	    {
	      *len = 5;
	      return ("mov %B0,%A0" CR_TAB
		      "clr %A0"     CR_TAB
		      "swap %B0"    CR_TAB
		      "ldi %3,0xf0" CR_TAB
		      "and %B0,%3");
	    }
	  *len = 6;
	  return ("mov %B0,%A0" CR_TAB
		  "clr %A0"     CR_TAB
		  "lsl %B0"     CR_TAB
		  "lsl %B0"     CR_TAB
		  "lsl %B0"     CR_TAB
		  "lsl %B0");

	case 13:
	  if (ldi_ok)
	    {
	      *len = 5;
	      return ("mov %B0,%A0" CR_TAB
		      "clr %A0"     CR_TAB
		      "swap %B0"    CR_TAB
		      "lsl %B0"     CR_TAB
		      "andi %B0,0xe0");
	    }
	  if (AVR_HAVE_MUL && scratch)
	    {
	      *len = 5;
	      return ("ldi %3,0x20" CR_TAB
		      "mul %A0,%3"  CR_TAB
		      "mov %B0,r0"  CR_TAB
		      "clr %A0"     CR_TAB
		      "clr __zero_reg__");
	    }
	  if (optimize_size && scratch)
	    break;  /* 5 */
	  if (scratch)
	    {
	      *len = 6;
	      return ("mov %B0,%A0" CR_TAB
		      "clr %A0"     CR_TAB
		      "swap %B0"    CR_TAB
		      "lsl %B0"     CR_TAB
		      "ldi %3,0xe0" CR_TAB
		      "and %B0,%3");
	    }
	  if (AVR_HAVE_MUL)
	    {
	      *len = 6;
	      return ("set"            CR_TAB
		      "bld r1,5"   CR_TAB
		      "mul %A0,r1" CR_TAB
		      "mov %B0,r0" CR_TAB
		      "clr %A0"    CR_TAB
		      "clr __zero_reg__");
	    }
	  *len = 7;
	  return ("mov %B0,%A0" CR_TAB
		  "clr %A0"     CR_TAB
		  "lsl %B0"     CR_TAB
		  "lsl %B0"     CR_TAB
		  "lsl %B0"     CR_TAB
		  "lsl %B0"     CR_TAB
		  "lsl %B0");

	case 14:
	  if (AVR_HAVE_MUL && ldi_ok)
	    {
	      *len = 5;
	      return ("ldi %B0,0x40" CR_TAB
		      "mul %A0,%B0"  CR_TAB
		      "mov %B0,r0"   CR_TAB
		      "clr %A0"      CR_TAB
		      "clr __zero_reg__");
	    }
	  if (AVR_HAVE_MUL && scratch)
	    {
	      *len = 5;
	      return ("ldi %3,0x40" CR_TAB
		      "mul %A0,%3"  CR_TAB
		      "mov %B0,r0"  CR_TAB
		      "clr %A0"     CR_TAB
		      "clr __zero_reg__");
	    }
	  if (optimize_size && ldi_ok)
	    {
	      *len = 5;
	      return ("mov %B0,%A0" CR_TAB
		      "ldi %A0,6" "\n1:\t"
		      "lsl %B0"     CR_TAB
		      "dec %A0"     CR_TAB
		      "brne 1b");
	    }
	  if (optimize_size && scratch)
	    break;  /* 5 */
	  *len = 6;
	  return ("clr %B0" CR_TAB
		  "lsr %A0" CR_TAB
		  "ror %B0" CR_TAB
		  "lsr %A0" CR_TAB
		  "ror %B0" CR_TAB
		  "clr %A0");

	case 15:
	  *len = 4;
	  return ("clr %B0" CR_TAB
		  "lsr %A0" CR_TAB
		  "ror %B0" CR_TAB
		  "clr %A0");
	}
      len = t;
    }
  out_shift_with_cnt ("lsl %A0" CR_TAB
                      "rol %B0", insn, operands, len, 2);
  return "";
}


/* 24-bit shift left */

const char*
avr_out_ashlpsi3 (rtx insn, rtx *op, int *plen)
{
  if (plen)
    *plen = 0;

  if (CONST_INT_P (op[2]))
    {
      switch (INTVAL (op[2]))
        {
        default:
          if (INTVAL (op[2]) < 24)
            break;

          return avr_asm_len ("clr %A0" CR_TAB
                              "clr %B0" CR_TAB
                              "clr %C0", op, plen, 3);

        case 8:
          {
            int reg0 = REGNO (op[0]);
            int reg1 = REGNO (op[1]);

            if (reg0 >= reg1)
              return avr_asm_len ("mov %C0,%B1"  CR_TAB
                                  "mov %B0,%A1"  CR_TAB
                                  "clr %A0", op, plen, 3);
            else
              return avr_asm_len ("clr %A0"      CR_TAB
                                  "mov %B0,%A1"  CR_TAB
                                  "mov %C0,%B1", op, plen, 3);
          }

        case 16:
          {
            int reg0 = REGNO (op[0]);
            int reg1 = REGNO (op[1]);

            if (reg0 + 2 != reg1)
              avr_asm_len ("mov %C0,%A0", op, plen, 1);

            return avr_asm_len ("clr %B0"  CR_TAB
                                "clr %A0", op, plen, 2);
          }

        case 23:
          return avr_asm_len ("clr %C0" CR_TAB
                              "lsr %A0" CR_TAB
                              "ror %C0" CR_TAB
                              "clr %B0" CR_TAB
                              "clr %A0", op, plen, 5);
        }
    }

  out_shift_with_cnt ("lsl %A0" CR_TAB
                      "rol %B0" CR_TAB
                      "rol %C0", insn, op, plen, 3);
  return "";
}


/* 32bit shift left ((long)x << i)   */

const char *
ashlsi3_out (rtx insn, rtx operands[], int *len)
{
  if (GET_CODE (operands[2]) == CONST_INT)
    {
      int k;
      int *t = len;

      if (!len)
	len = &k;

      switch (INTVAL (operands[2]))
	{
	default:
	  if (INTVAL (operands[2]) < 32)
	    break;

	  if (AVR_HAVE_MOVW)
	    return *len = 3, ("clr %D0" CR_TAB
			      "clr %C0" CR_TAB
			      "movw %A0,%C0");
	  *len = 4;
	  return ("clr %D0" CR_TAB
		  "clr %C0" CR_TAB
		  "clr %B0" CR_TAB
		  "clr %A0");

	case 8:
	  {
	    int reg0 = true_regnum (operands[0]);
	    int reg1 = true_regnum (operands[1]);
	    *len = 4;
	    if (reg0 >= reg1)
	      return ("mov %D0,%C1"  CR_TAB
		      "mov %C0,%B1"  CR_TAB
		      "mov %B0,%A1"  CR_TAB
		      "clr %A0");
	    else
	      return ("clr %A0"      CR_TAB
		      "mov %B0,%A1"  CR_TAB
		      "mov %C0,%B1"  CR_TAB
		      "mov %D0,%C1");
	  }

	case 16:
	  {
	    int reg0 = true_regnum (operands[0]);
	    int reg1 = true_regnum (operands[1]);
	    if (reg0 + 2 == reg1)
	      return *len = 2, ("clr %B0"      CR_TAB
				"clr %A0");
	    if (AVR_HAVE_MOVW)
	      return *len = 3, ("movw %C0,%A1" CR_TAB
				"clr %B0"      CR_TAB
				"clr %A0");
	    else
	      return *len = 4, ("mov %C0,%A1"  CR_TAB
				"mov %D0,%B1"  CR_TAB
				"clr %B0"      CR_TAB
				"clr %A0");
	  }

	case 24:
	  *len = 4;
	  return ("mov %D0,%A1"  CR_TAB
		  "clr %C0"      CR_TAB
		  "clr %B0"      CR_TAB
		  "clr %A0");

	case 31:
	  *len = 6;
	  return ("clr %D0" CR_TAB
		  "lsr %A0" CR_TAB
		  "ror %D0" CR_TAB
		  "clr %C0" CR_TAB
		  "clr %B0" CR_TAB
		  "clr %A0");
	}
      len = t;
    }
  out_shift_with_cnt ("lsl %A0" CR_TAB
                      "rol %B0" CR_TAB
                      "rol %C0" CR_TAB
                      "rol %D0", insn, operands, len, 4);
  return "";
}

/* 8bit arithmetic shift right  ((signed char)x >> i) */

const char *
ashrqi3_out (rtx insn, rtx operands[], int *len)
{
  if (GET_CODE (operands[2]) == CONST_INT)
    {
      int k;

      if (!len)
	len = &k;

      switch (INTVAL (operands[2]))
	{
	case 1:
	  *len = 1;
	  return "asr %0";

	case 2:
	  *len = 2;
	  return ("asr %0" CR_TAB
		  "asr %0");

	case 3:
	  *len = 3;
	  return ("asr %0" CR_TAB
		  "asr %0" CR_TAB
		  "asr %0");

	case 4:
	  *len = 4;
	  return ("asr %0" CR_TAB
		  "asr %0" CR_TAB
		  "asr %0" CR_TAB
		  "asr %0");

	case 5:
	  *len = 5;
	  return ("asr %0" CR_TAB
		  "asr %0" CR_TAB
		  "asr %0" CR_TAB
		  "asr %0" CR_TAB
		  "asr %0");

	case 6:
	  *len = 4;
	  return ("bst %0,6"  CR_TAB
		  "lsl %0"    CR_TAB
		  "sbc %0,%0" CR_TAB
		  "bld %0,0");

	default:
	  if (INTVAL (operands[2]) < 8)
	    break;

	  /* fall through */

	case 7:
	  *len = 2;
	  return ("lsl %0" CR_TAB
		  "sbc %0,%0");
	}
    }
  else if (CONSTANT_P (operands[2]))
    fatal_insn ("internal compiler error.  Incorrect shift:", insn);

  out_shift_with_cnt ("asr %0",
                      insn, operands, len, 1);
  return "";
}


/* 16bit arithmetic shift right  ((signed short)x >> i) */

const char *
ashrhi3_out (rtx insn, rtx operands[], int *len)
{
  if (GET_CODE (operands[2]) == CONST_INT)
    {
      int scratch = (GET_CODE (PATTERN (insn)) == PARALLEL);
      int ldi_ok = test_hard_reg_class (LD_REGS, operands[0]);
      int k;
      int *t = len;

      if (!len)
	len = &k;

      switch (INTVAL (operands[2]))
	{
	case 4:
	case 5:
	  /* XXX try to optimize this too? */
	  break;

	case 6:
	  if (optimize_size)
	    break;  /* scratch ? 5 : 6 */
	  *len = 8;
	  return ("mov __tmp_reg__,%A0" CR_TAB
		  "mov %A0,%B0"         CR_TAB
		  "lsl __tmp_reg__"     CR_TAB
		  "rol %A0"             CR_TAB
		  "sbc %B0,%B0"         CR_TAB
		  "lsl __tmp_reg__"     CR_TAB
		  "rol %A0"             CR_TAB
		  "rol %B0");

	case 7:
	  *len = 4;
	  return ("lsl %A0"     CR_TAB
		  "mov %A0,%B0" CR_TAB
		  "rol %A0"     CR_TAB
		  "sbc %B0,%B0");

	case 8:
	  {
	    int reg0 = true_regnum (operands[0]);
	    int reg1 = true_regnum (operands[1]);

	    if (reg0 == reg1)
	      return *len = 3, ("mov %A0,%B0" CR_TAB
				"lsl %B0"     CR_TAB
				"sbc %B0,%B0");
	    else
	      return *len = 4, ("mov %A0,%B1" CR_TAB
			        "clr %B0"     CR_TAB
			        "sbrc %A0,7"  CR_TAB
			        "dec %B0");
	  }

	case 9:
	  *len = 4;
	  return ("mov %A0,%B0" CR_TAB
		  "lsl %B0"      CR_TAB
		  "sbc %B0,%B0" CR_TAB
		  "asr %A0");

	case 10:
	  *len = 5;
	  return ("mov %A0,%B0" CR_TAB
		  "lsl %B0"     CR_TAB
		  "sbc %B0,%B0" CR_TAB
		  "asr %A0"     CR_TAB
		  "asr %A0");

	case 11:
	  if (AVR_HAVE_MUL && ldi_ok)
	    {
	      *len = 5;
	      return ("ldi %A0,0x20" CR_TAB
		      "muls %B0,%A0" CR_TAB
		      "mov %A0,r1"   CR_TAB
		      "sbc %B0,%B0"  CR_TAB
		      "clr __zero_reg__");
	    }
	  if (optimize_size && scratch)
	    break;  /* 5 */
	  *len = 6;
	  return ("mov %A0,%B0" CR_TAB
		  "lsl %B0"     CR_TAB
		  "sbc %B0,%B0" CR_TAB
		  "asr %A0"     CR_TAB
		  "asr %A0"     CR_TAB
		  "asr %A0");

	case 12:
	  if (AVR_HAVE_MUL && ldi_ok)
	    {
	      *len = 5;
	      return ("ldi %A0,0x10" CR_TAB
		      "muls %B0,%A0" CR_TAB
		      "mov %A0,r1"   CR_TAB
		      "sbc %B0,%B0"  CR_TAB
		      "clr __zero_reg__");
	    }
	  if (optimize_size && scratch)
	    break;  /* 5 */
	  *len = 7;
	  return ("mov %A0,%B0" CR_TAB
		  "lsl %B0"     CR_TAB
		  "sbc %B0,%B0" CR_TAB
		  "asr %A0"     CR_TAB
		  "asr %A0"     CR_TAB
		  "asr %A0"     CR_TAB
		  "asr %A0");

	case 13:
	  if (AVR_HAVE_MUL && ldi_ok)
	    {
	      *len = 5;
	      return ("ldi %A0,0x08" CR_TAB
		      "muls %B0,%A0" CR_TAB
		      "mov %A0,r1"   CR_TAB
		      "sbc %B0,%B0"  CR_TAB
		      "clr __zero_reg__");
	    }
	  if (optimize_size)
	    break;  /* scratch ? 5 : 7 */
	  *len = 8;
	  return ("mov %A0,%B0" CR_TAB
		  "lsl %B0"     CR_TAB
		  "sbc %B0,%B0" CR_TAB
		  "asr %A0"     CR_TAB
		  "asr %A0"     CR_TAB
		  "asr %A0"     CR_TAB
		  "asr %A0"     CR_TAB
		  "asr %A0");

	case 14:
	  *len = 5;
	  return ("lsl %B0"     CR_TAB
		  "sbc %A0,%A0" CR_TAB
		  "lsl %B0"     CR_TAB
		  "mov %B0,%A0" CR_TAB
		  "rol %A0");

	default:
	  if (INTVAL (operands[2]) < 16)
	    break;

	  /* fall through */

	case 15:
	  return *len = 3, ("lsl %B0"     CR_TAB
			    "sbc %A0,%A0" CR_TAB
			    "mov %B0,%A0");
	}
      len = t;
    }
  out_shift_with_cnt ("asr %B0" CR_TAB
                      "ror %A0", insn, operands, len, 2);
  return "";
}


/* 24-bit arithmetic shift right */

const char*
avr_out_ashrpsi3 (rtx insn, rtx *op, int *plen)
{
  int dest = REGNO (op[0]);
  int src = REGNO (op[1]);

  if (CONST_INT_P (op[2]))
    {
      if (plen)
        *plen = 0;

      switch (INTVAL (op[2]))
        {
        case 8:
          if (dest <= src)
            return avr_asm_len ("mov %A0,%B1" CR_TAB
                                "mov %B0,%C1" CR_TAB
                                "clr %C0"     CR_TAB
                                "sbrc %B0,7"  CR_TAB
                                "dec %C0", op, plen, 5);
          else
            return avr_asm_len ("clr %C0"     CR_TAB
                                "sbrc %C1,7"  CR_TAB
                                "dec %C0"     CR_TAB
                                "mov %B0,%C1" CR_TAB
                                "mov %A0,%B1", op, plen, 5);

        case 16:
          if (dest != src + 2)
            avr_asm_len ("mov %A0,%C1", op, plen, 1);

          return avr_asm_len ("clr %B0"     CR_TAB
                              "sbrc %A0,7"  CR_TAB
                              "com %B0"     CR_TAB
                              "mov %C0,%B0", op, plen, 4);

        default:
          if (INTVAL (op[2]) < 24)
            break;

          /* fall through */

        case 23:
          return avr_asm_len ("lsl %C0"     CR_TAB
                              "sbc %A0,%A0" CR_TAB
                              "mov %B0,%A0" CR_TAB
                              "mov %C0,%A0", op, plen, 4);
        } /* switch */
    }

  out_shift_with_cnt ("asr %C0" CR_TAB
                      "ror %B0" CR_TAB
                      "ror %A0", insn, op, plen, 3);
  return "";
}


/* 32-bit arithmetic shift right  ((signed long)x >> i) */

const char *
ashrsi3_out (rtx insn, rtx operands[], int *len)
{
  if (GET_CODE (operands[2]) == CONST_INT)
    {
      int k;
      int *t = len;

      if (!len)
	len = &k;

      switch (INTVAL (operands[2]))
	{
	case 8:
	  {
	    int reg0 = true_regnum (operands[0]);
	    int reg1 = true_regnum (operands[1]);
	    *len=6;
	    if (reg0 <= reg1)
	      return ("mov %A0,%B1" CR_TAB
		      "mov %B0,%C1" CR_TAB
		      "mov %C0,%D1" CR_TAB
		      "clr %D0"     CR_TAB
		      "sbrc %C0,7"  CR_TAB
		      "dec %D0");
	    else
	      return ("clr %D0"     CR_TAB
		      "sbrc %D1,7"  CR_TAB
		      "dec %D0"     CR_TAB
		      "mov %C0,%D1" CR_TAB
		      "mov %B0,%C1" CR_TAB
		      "mov %A0,%B1");
	  }

	case 16:
	  {
	    int reg0 = true_regnum (operands[0]);
	    int reg1 = true_regnum (operands[1]);

	    if (reg0 == reg1 + 2)
	      return *len = 4, ("clr %D0"     CR_TAB
				"sbrc %B0,7"  CR_TAB
				"com %D0"     CR_TAB
				"mov %C0,%D0");
	    if (AVR_HAVE_MOVW)
	      return *len = 5, ("movw %A0,%C1" CR_TAB
				"clr %D0"      CR_TAB
				"sbrc %B0,7"   CR_TAB
				"com %D0"      CR_TAB
				"mov %C0,%D0");
	    else
	      return *len = 6, ("mov %B0,%D1" CR_TAB
				"mov %A0,%C1" CR_TAB
				"clr %D0"     CR_TAB
				"sbrc %B0,7"  CR_TAB
				"com %D0"     CR_TAB
				"mov %C0,%D0");
	  }

	case 24:
	  return *len = 6, ("mov %A0,%D1" CR_TAB
			    "clr %D0"     CR_TAB
			    "sbrc %A0,7"  CR_TAB
			    "com %D0"     CR_TAB
			    "mov %B0,%D0" CR_TAB
			    "mov %C0,%D0");

	default:
	  if (INTVAL (operands[2]) < 32)
	    break;

	  /* fall through */

	case 31:
	  if (AVR_HAVE_MOVW)
	    return *len = 4, ("lsl %D0"     CR_TAB
			      "sbc %A0,%A0" CR_TAB
			      "mov %B0,%A0" CR_TAB
			      "movw %C0,%A0");
	  else
	    return *len = 5, ("lsl %D0"     CR_TAB
			      "sbc %A0,%A0" CR_TAB
			      "mov %B0,%A0" CR_TAB
			      "mov %C0,%A0" CR_TAB
			      "mov %D0,%A0");
	}
      len = t;
    }
  out_shift_with_cnt ("asr %D0" CR_TAB
                      "ror %C0" CR_TAB
                      "ror %B0" CR_TAB
                      "ror %A0", insn, operands, len, 4);
  return "";
}

/* 8-bit logic shift right ((unsigned char)x >> i) */

const char *
lshrqi3_out (rtx insn, rtx operands[], int *len)
{
  if (GET_CODE (operands[2]) == CONST_INT)
    {
      int k;

      if (!len)
	len = &k;

      switch (INTVAL (operands[2]))
	{
	default:
	  if (INTVAL (operands[2]) < 8)
	    break;

	  *len = 1;
	  return "clr %0";

	case 1:
	  *len = 1;
	  return "lsr %0";

	case 2:
	  *len = 2;
	  return ("lsr %0" CR_TAB
		  "lsr %0");
	case 3:
	  *len = 3;
	  return ("lsr %0" CR_TAB
		  "lsr %0" CR_TAB
		  "lsr %0");

	case 4:
	  if (test_hard_reg_class (LD_REGS, operands[0]))
	    {
	      *len=2;
	      return ("swap %0" CR_TAB
		      "andi %0,0x0f");
	    }
	  *len = 4;
	  return ("lsr %0" CR_TAB
		  "lsr %0" CR_TAB
		  "lsr %0" CR_TAB
		  "lsr %0");

	case 5:
	  if (test_hard_reg_class (LD_REGS, operands[0]))
	    {
	      *len = 3;
	      return ("swap %0" CR_TAB
		      "lsr %0"  CR_TAB
		      "andi %0,0x7");
	    }
	  *len = 5;
	  return ("lsr %0" CR_TAB
		  "lsr %0" CR_TAB
		  "lsr %0" CR_TAB
		  "lsr %0" CR_TAB
		  "lsr %0");

	case 6:
	  if (test_hard_reg_class (LD_REGS, operands[0]))
	    {
	      *len = 4;
	      return ("swap %0" CR_TAB
		      "lsr %0"  CR_TAB
		      "lsr %0"  CR_TAB
		      "andi %0,0x3");
	    }
	  *len = 6;
	  return ("lsr %0" CR_TAB
		  "lsr %0" CR_TAB
		  "lsr %0" CR_TAB
		  "lsr %0" CR_TAB
		  "lsr %0" CR_TAB
		  "lsr %0");

	case 7:
	  *len = 3;
	  return ("rol %0" CR_TAB
		  "clr %0" CR_TAB
		  "rol %0");
	}
    }
  else if (CONSTANT_P (operands[2]))
    fatal_insn ("internal compiler error.  Incorrect shift:", insn);

  out_shift_with_cnt ("lsr %0",
                      insn, operands, len, 1);
  return "";
}

/* 16-bit logic shift right ((unsigned short)x >> i) */

const char *
lshrhi3_out (rtx insn, rtx operands[], int *len)
{
  if (GET_CODE (operands[2]) == CONST_INT)
    {
      int scratch = (GET_CODE (PATTERN (insn)) == PARALLEL);
      int ldi_ok = test_hard_reg_class (LD_REGS, operands[0]);
      int k;
      int *t = len;

      if (!len)
	len = &k;

      switch (INTVAL (operands[2]))
	{
	default:
	  if (INTVAL (operands[2]) < 16)
	    break;

	  *len = 2;
	  return ("clr %B0" CR_TAB
		  "clr %A0");

	case 4:
	  if (optimize_size && scratch)
	    break;  /* 5 */
	  if (ldi_ok)
	    {
	      *len = 6;
	      return ("swap %B0"      CR_TAB
		      "swap %A0"      CR_TAB
		      "andi %A0,0x0f" CR_TAB
		      "eor %A0,%B0"   CR_TAB
		      "andi %B0,0x0f" CR_TAB
		      "eor %A0,%B0");
	    }
	  if (scratch)
	    {
	      *len = 7;
	      return ("swap %B0"    CR_TAB
		      "swap %A0"    CR_TAB
		      "ldi %3,0x0f" CR_TAB
		      "and %A0,%3"      CR_TAB
		      "eor %A0,%B0" CR_TAB
		      "and %B0,%3"      CR_TAB
		      "eor %A0,%B0");
	    }
	  break;  /* optimize_size ? 6 : 8 */

	case 5:
	  if (optimize_size)
	    break;  /* scratch ? 5 : 6 */
	  if (ldi_ok)
	    {
	      *len = 8;
	      return ("lsr %B0"       CR_TAB
		      "ror %A0"       CR_TAB
		      "swap %B0"      CR_TAB
		      "swap %A0"      CR_TAB
		      "andi %A0,0x0f" CR_TAB
		      "eor %A0,%B0"   CR_TAB
		      "andi %B0,0x0f" CR_TAB
		      "eor %A0,%B0");
	    }
	  if (scratch)
	    {
	      *len = 9;
	      return ("lsr %B0"     CR_TAB
		      "ror %A0"     CR_TAB
		      "swap %B0"    CR_TAB
		      "swap %A0"    CR_TAB
		      "ldi %3,0x0f" CR_TAB
		      "and %A0,%3"      CR_TAB
		      "eor %A0,%B0" CR_TAB
		      "and %B0,%3"      CR_TAB
		      "eor %A0,%B0");
	    }
	  break;  /* 10 */

	case 6:
	  if (optimize_size)
	    break;  /* scratch ? 5 : 6 */
	  *len = 9;
	  return ("clr __tmp_reg__" CR_TAB
		  "lsl %A0"         CR_TAB
		  "rol %B0"         CR_TAB
		  "rol __tmp_reg__" CR_TAB
		  "lsl %A0"         CR_TAB
		  "rol %B0"         CR_TAB
		  "rol __tmp_reg__" CR_TAB
		  "mov %A0,%B0"     CR_TAB
		  "mov %B0,__tmp_reg__");

	case 7:
	  *len = 5;
	  return ("lsl %A0"     CR_TAB
		  "mov %A0,%B0" CR_TAB
		  "rol %A0"     CR_TAB
		  "sbc %B0,%B0" CR_TAB
		  "neg %B0");

	case 8:
	  return *len = 2, ("mov %A0,%B1" CR_TAB
			    "clr %B0");

	case 9:
	  *len = 3;
	  return ("mov %A0,%B0" CR_TAB
		  "clr %B0"     CR_TAB
		  "lsr %A0");

	case 10:
	  *len = 4;
	  return ("mov %A0,%B0" CR_TAB
		  "clr %B0"     CR_TAB
		  "lsr %A0"     CR_TAB
		  "lsr %A0");

	case 11:
	  *len = 5;
	  return ("mov %A0,%B0" CR_TAB
		  "clr %B0"     CR_TAB
		  "lsr %A0"     CR_TAB
		  "lsr %A0"     CR_TAB
		  "lsr %A0");

	case 12:
	  if (ldi_ok)
	    {
	      *len = 4;
	      return ("mov %A0,%B0" CR_TAB
		      "clr %B0"     CR_TAB
		      "swap %A0"    CR_TAB
		      "andi %A0,0x0f");
	    }
	  if (scratch)
	    {
	      *len = 5;
	      return ("mov %A0,%B0" CR_TAB
		      "clr %B0"     CR_TAB
		      "swap %A0"    CR_TAB
		      "ldi %3,0x0f" CR_TAB
		      "and %A0,%3");
	    }
	  *len = 6;
	  return ("mov %A0,%B0" CR_TAB
		  "clr %B0"     CR_TAB
		  "lsr %A0"     CR_TAB
		  "lsr %A0"     CR_TAB
		  "lsr %A0"     CR_TAB
		  "lsr %A0");

	case 13:
	  if (ldi_ok)
	    {
	      *len = 5;
	      return ("mov %A0,%B0" CR_TAB
		      "clr %B0"     CR_TAB
		      "swap %A0"    CR_TAB
		      "lsr %A0"     CR_TAB
		      "andi %A0,0x07");
	    }
	  if (AVR_HAVE_MUL && scratch)
	    {
	      *len = 5;
	      return ("ldi %3,0x08" CR_TAB
		      "mul %B0,%3"  CR_TAB
		      "mov %A0,r1"  CR_TAB
		      "clr %B0"     CR_TAB
		      "clr __zero_reg__");
	    }
	  if (optimize_size && scratch)
	    break;  /* 5 */
	  if (scratch)
	    {
	      *len = 6;
	      return ("mov %A0,%B0" CR_TAB
		      "clr %B0"     CR_TAB
		      "swap %A0"    CR_TAB
		      "lsr %A0"     CR_TAB
		      "ldi %3,0x07" CR_TAB
		      "and %A0,%3");
	    }
	  if (AVR_HAVE_MUL)
	    {
	      *len = 6;
	      return ("set"            CR_TAB
		      "bld r1,3"   CR_TAB
		      "mul %B0,r1" CR_TAB
		      "mov %A0,r1" CR_TAB
		      "clr %B0"    CR_TAB
		      "clr __zero_reg__");
	    }
	  *len = 7;
	  return ("mov %A0,%B0" CR_TAB
		  "clr %B0"     CR_TAB
		  "lsr %A0"     CR_TAB
		  "lsr %A0"     CR_TAB
		  "lsr %A0"     CR_TAB
		  "lsr %A0"     CR_TAB
		  "lsr %A0");

	case 14:
	  if (AVR_HAVE_MUL && ldi_ok)
	    {
	      *len = 5;
	      return ("ldi %A0,0x04" CR_TAB
		      "mul %B0,%A0"  CR_TAB
		      "mov %A0,r1"   CR_TAB
		      "clr %B0"      CR_TAB
		      "clr __zero_reg__");
	    }
	  if (AVR_HAVE_MUL && scratch)
	    {
	      *len = 5;
	      return ("ldi %3,0x04" CR_TAB
		      "mul %B0,%3"  CR_TAB
		      "mov %A0,r1"  CR_TAB
		      "clr %B0"     CR_TAB
		      "clr __zero_reg__");
	    }
	  if (optimize_size && ldi_ok)
	    {
	      *len = 5;
	      return ("mov %A0,%B0" CR_TAB
		      "ldi %B0,6" "\n1:\t"
		      "lsr %A0"     CR_TAB
		      "dec %B0"     CR_TAB
		      "brne 1b");
	    }
	  if (optimize_size && scratch)
	    break;  /* 5 */
	  *len = 6;
	  return ("clr %A0" CR_TAB
		  "lsl %B0" CR_TAB
		  "rol %A0" CR_TAB
		  "lsl %B0" CR_TAB
		  "rol %A0" CR_TAB
		  "clr %B0");

	case 15:
	  *len = 4;
	  return ("clr %A0" CR_TAB
		  "lsl %B0" CR_TAB
		  "rol %A0" CR_TAB
		  "clr %B0");
	}
      len = t;
    }
  out_shift_with_cnt ("lsr %B0" CR_TAB
                      "ror %A0", insn, operands, len, 2);
  return "";
}


/* 24-bit logic shift right */

const char*
avr_out_lshrpsi3 (rtx insn, rtx *op, int *plen)
{
  int dest = REGNO (op[0]);
  int src = REGNO (op[1]);

  if (CONST_INT_P (op[2]))
    {
      if (plen)
        *plen = 0;

      switch (INTVAL (op[2]))
        {
        case 8:
          if (dest <= src)
            return avr_asm_len ("mov %A0,%B1" CR_TAB
                                "mov %B0,%C1" CR_TAB
                                "clr %C0", op, plen, 3);
          else
            return avr_asm_len ("clr %C0"     CR_TAB
                                "mov %B0,%C1" CR_TAB
                                "mov %A0,%B1", op, plen, 3);

        case 16:
          if (dest != src + 2)
            avr_asm_len ("mov %A0,%C1", op, plen, 1);

          return avr_asm_len ("clr %B0"  CR_TAB
                              "clr %C0", op, plen, 2);

        default:
          if (INTVAL (op[2]) < 24)
            break;

          /* fall through */

        case 23:
          return avr_asm_len ("clr %A0"    CR_TAB
                              "sbrc %C0,7" CR_TAB
                              "inc %A0"    CR_TAB
                              "clr %B0"    CR_TAB
                              "clr %C0", op, plen, 5);
        } /* switch */
    }

  out_shift_with_cnt ("lsr %C0" CR_TAB
                      "ror %B0" CR_TAB
                      "ror %A0", insn, op, plen, 3);
  return "";
}


/* 32-bit logic shift right ((unsigned int)x >> i) */

const char *
lshrsi3_out (rtx insn, rtx operands[], int *len)
{
  if (GET_CODE (operands[2]) == CONST_INT)
    {
      int k;
      int *t = len;

      if (!len)
	len = &k;

      switch (INTVAL (operands[2]))
	{
	default:
	  if (INTVAL (operands[2]) < 32)
	    break;

	  if (AVR_HAVE_MOVW)
	    return *len = 3, ("clr %D0" CR_TAB
			      "clr %C0" CR_TAB
			      "movw %A0,%C0");
	  *len = 4;
	  return ("clr %D0" CR_TAB
		  "clr %C0" CR_TAB
		  "clr %B0" CR_TAB
		  "clr %A0");

	case 8:
	  {
	    int reg0 = true_regnum (operands[0]);
	    int reg1 = true_regnum (operands[1]);
	    *len = 4;
	    if (reg0 <= reg1)
	      return ("mov %A0,%B1" CR_TAB
		      "mov %B0,%C1" CR_TAB
		      "mov %C0,%D1" CR_TAB
		      "clr %D0");
	    else
	      return ("clr %D0"     CR_TAB
		      "mov %C0,%D1" CR_TAB
		      "mov %B0,%C1" CR_TAB
		      "mov %A0,%B1");
	  }

	case 16:
	  {
	    int reg0 = true_regnum (operands[0]);
	    int reg1 = true_regnum (operands[1]);

	    if (reg0 == reg1 + 2)
	      return *len = 2, ("clr %C0"     CR_TAB
				"clr %D0");
	    if (AVR_HAVE_MOVW)
	      return *len = 3, ("movw %A0,%C1" CR_TAB
				"clr %C0"      CR_TAB
				"clr %D0");
	    else
	      return *len = 4, ("mov %B0,%D1" CR_TAB
				"mov %A0,%C1" CR_TAB
				"clr %C0"     CR_TAB
				"clr %D0");
	  }

	case 24:
	  return *len = 4, ("mov %A0,%D1" CR_TAB
			    "clr %B0"     CR_TAB
			    "clr %C0"     CR_TAB
			    "clr %D0");

	case 31:
	  *len = 6;
	  return ("clr %A0"    CR_TAB
		  "sbrc %D0,7" CR_TAB
		  "inc %A0"    CR_TAB
		  "clr %B0"    CR_TAB
		  "clr %C0"    CR_TAB
		  "clr %D0");
	}
      len = t;
    }
  out_shift_with_cnt ("lsr %D0" CR_TAB
                      "ror %C0" CR_TAB
                      "ror %B0" CR_TAB
                      "ror %A0", insn, operands, len, 4);
  return "";
}


/* Output addition of register XOP[0] and compile time constant XOP[2].
   CODE == PLUS:  perform addition by using ADD instructions or
   CODE == MINUS: perform addition by using SUB instructions:

      XOP[0] = XOP[0] + XOP[2]

   Or perform addition/subtraction with register XOP[2] depending on CODE:

      XOP[0] = XOP[0] +/- XOP[2]

   If PLEN == NULL, print assembler instructions to perform the operation;
   otherwise, set *PLEN to the length of the instruction sequence (in words)
   printed with PLEN == NULL.  XOP[3] is an 8-bit scratch register or NULL_RTX.
   Set *PCC to effect on cc0 according to respective CC_* insn attribute.

   CODE_SAT == UNKNOWN: Perform ordinary, non-saturating operation.
   CODE_SAT != UNKNOWN: Perform operation and saturate according to CODE_SAT.
   If  CODE_SAT != UNKNOWN  then SIGN contains the sign of the summand resp.
   the subtrahend in the original insn, provided it is a compile time constant.
   In all other cases, SIGN is 0.

   If OUT_LABEL is true, print the final 0: label which is needed for
   saturated addition / subtraction.  The only case where OUT_LABEL = false
   is useful is for saturated addition / subtraction performed during
   fixed-point rounding, cf. `avr_out_round'.  */

static void
avr_out_plus_1 (rtx *xop, int *plen, enum rtx_code code, int *pcc,
                enum rtx_code code_sat, int sign, bool out_label)
{
  /* MODE of the operation.  */
  enum machine_mode mode = GET_MODE (xop[0]);

  /* INT_MODE of the same size.  */
  enum machine_mode imode = int_mode_for_mode (mode);

  /* Number of bytes to operate on.  */
  int i, n_bytes = GET_MODE_SIZE (mode);

  /* Value (0..0xff) held in clobber register op[3] or -1 if unknown.  */
  int clobber_val = -1;

  /* op[0]: 8-bit destination register
     op[1]: 8-bit const int
     op[2]: 8-bit scratch register */
  rtx op[3];

  /* Started the operation?  Before starting the operation we may skip
     adding 0.  This is no more true after the operation started because
     carry must be taken into account.  */
  bool started = false;

  /* Value to add.  There are two ways to add VAL: R += VAL and R -= -VAL.  */
  rtx xval = xop[2];

  /* Output a BRVC instruction.  Only needed with saturation.  */
  bool out_brvc = true;

  if (plen)
    *plen = 0;

  if (REG_P (xop[2]))
    {
      *pcc = MINUS == code ? (int) CC_SET_CZN : (int) CC_CLOBBER;

      for (i = 0; i < n_bytes; i++)
        {
          /* We operate byte-wise on the destination.  */
          op[0] = simplify_gen_subreg (QImode, xop[0], mode, i);
          op[1] = simplify_gen_subreg (QImode, xop[2], mode, i);

          if (i == 0)
            avr_asm_len (code == PLUS ? "add %0,%1" : "sub %0,%1",
                         op, plen, 1);
          else
            avr_asm_len (code == PLUS ? "adc %0,%1" : "sbc %0,%1",
                         op, plen, 1);
        }

      if (reg_overlap_mentioned_p (xop[0], xop[2]))
        {
          gcc_assert (REGNO (xop[0]) == REGNO (xop[2]));

          if (MINUS == code)
            return;
        }

      goto saturate;
    }

  /* Except in the case of ADIW with 16-bit register (see below)
     addition does not set cc0 in a usable way.  */

  *pcc = (MINUS == code) ? CC_SET_CZN : CC_CLOBBER;

  if (CONST_FIXED_P (xval))
    xval = avr_to_int_mode (xval);

  /* Adding/Subtracting zero is a no-op.  */

  if (xval == const0_rtx)
    {
      *pcc = CC_NONE;
      return;
    }

  if (MINUS == code)
    xval = simplify_unary_operation (NEG, imode, xval, imode);

  op[2] = xop[3];

  if (SS_PLUS == code_sat && MINUS == code
      && sign < 0
      && 0x80 == (INTVAL (simplify_gen_subreg (QImode, xval, imode, n_bytes-1))
                  & GET_MODE_MASK (QImode)))
    {
      /* We compute x + 0x80 by means of SUB instructions.  We negated the
         constant subtrahend above and are left with  x - (-128)  so that we
         need something like SUBI r,128 which does not exist because SUBI sets
         V according to the sign of the subtrahend.  Notice the only case
         where this must be done is when NEG overflowed in case [2s] because
         the V computation needs the right sign of the subtrahend.  */

      rtx msb = simplify_gen_subreg (QImode, xop[0], mode, n_bytes-1);

      avr_asm_len ("subi %0,128" CR_TAB
                   "brmi 0f", &msb, plen, 2);
      out_brvc = false;

      goto saturate;
    }

  for (i = 0; i < n_bytes; i++)
    {
      /* We operate byte-wise on the destination.  */
      rtx reg8 = simplify_gen_subreg (QImode, xop[0], mode, i);
      rtx xval8 = simplify_gen_subreg (QImode, xval, imode, i);

      /* 8-bit value to operate with this byte. */
      unsigned int val8 = UINTVAL (xval8) & GET_MODE_MASK (QImode);

      /* Registers R16..R31 can operate with immediate.  */
      bool ld_reg_p = test_hard_reg_class (LD_REGS, reg8);

      op[0] = reg8;
      op[1] = gen_int_mode (val8, QImode);

      /* To get usable cc0 no low-bytes must have been skipped.  */

      if (i && !started)
        *pcc = CC_CLOBBER;

      if (!started
          && i % 2 == 0
          && i + 2 <= n_bytes
          && test_hard_reg_class (ADDW_REGS, reg8))
        {
          rtx xval16 = simplify_gen_subreg (HImode, xval, imode, i);
          unsigned int val16 = UINTVAL (xval16) & GET_MODE_MASK (HImode);

          /* Registers R24, X, Y, Z can use ADIW/SBIW with constants < 64
             i.e. operate word-wise.  */

          if (val16 < 64)
            {
              if (val16 != 0)
                {
                  started = true;
                  avr_asm_len (code == PLUS ? "adiw %0,%1" : "sbiw %0,%1",
                               op, plen, 1);

                  if (n_bytes == 2 && PLUS == code)
                    *pcc = CC_SET_CZN;
                }

              i++;
              continue;
            }
        }

      if (val8 == 0)
        {
          if (started)
            avr_asm_len (code == PLUS
                         ? "adc %0,__zero_reg__" : "sbc %0,__zero_reg__",
                         op, plen, 1);
          continue;
        }
      else if ((val8 == 1 || val8 == 0xff)
               && UNKNOWN == code_sat
               && !started
               && i == n_bytes - 1)
        {
          avr_asm_len ((code == PLUS) ^ (val8 == 1) ? "dec %0" : "inc %0",
                       op, plen, 1);
          *pcc = CC_CLOBBER;
          break;
        }

      switch (code)
        {
        case PLUS:

          gcc_assert (plen != NULL || (op[2] && REG_P (op[2])));

          if (plen != NULL && UNKNOWN != code_sat)
            {
              /* This belongs to the x + 0x80 corner case.  The code with
                 ADD instruction is not smaller, thus make this case
                 expensive so that the caller won't pick it.  */

              *plen += 10;
              break;
            }

          if (clobber_val != (int) val8)
            avr_asm_len ("ldi %2,%1", op, plen, 1);
          clobber_val = (int) val8;

          avr_asm_len (started ? "adc %0,%2" : "add %0,%2", op, plen, 1);

          break; /* PLUS */

        case MINUS:

          if (ld_reg_p)
            avr_asm_len (started ? "sbci %0,%1" : "subi %0,%1", op, plen, 1);
          else
            {
              gcc_assert (plen != NULL || REG_P (op[2]));

              if (clobber_val != (int) val8)
                avr_asm_len ("ldi %2,%1", op, plen, 1);
              clobber_val = (int) val8;

              avr_asm_len (started ? "sbc %0,%2" : "sub %0,%2", op, plen, 1);
            }

          break; /* MINUS */

        default:
          /* Unknown code */
          gcc_unreachable();
        }

      started = true;

    } /* for all sub-bytes */

 saturate:

  if (UNKNOWN == code_sat)
    return;

  *pcc = (int) CC_CLOBBER;

  /* Vanilla addition/subtraction is done.  We are left with saturation.

     We have to compute  A = A <op> B  where  A  is a register and
     B is a register or a non-zero compile time constant CONST.
     A is register class "r" if unsigned && B is REG.  Otherwise, A is in "d".
     B stands for the original operand $2 in INSN.  In the case of B = CONST,
     SIGN in { -1, 1 } is the sign of B.  Otherwise, SIGN is 0.

     CODE is the instruction flavor we use in the asm sequence to perform <op>.


     unsigned
     operation        |  code |  sat if  |    b is      | sat value |  case
     -----------------+-------+----------+--------------+-----------+-------
     +  as  a + b     |  add  |  C == 1  |  const, reg  | u+ = 0xff |  [1u]
     +  as  a - (-b)  |  sub  |  C == 0  |  const       | u+ = 0xff |  [2u]
     -  as  a - b     |  sub  |  C == 1  |  const, reg  | u- = 0    |  [3u]
     -  as  a + (-b)  |  add  |  C == 0  |  const       | u- = 0    |  [4u]


     signed
     operation        |  code |  sat if  |    b is      | sat value |  case
     -----------------+-------+----------+--------------+-----------+-------
     +  as  a + b     |  add  |  V == 1  |  const, reg  | s+        |  [1s]
     +  as  a - (-b)  |  sub  |  V == 1  |  const       | s+        |  [2s]
     -  as  a - b     |  sub  |  V == 1  |  const, reg  | s-        |  [3s]
     -  as  a + (-b)  |  add  |  V == 1  |  const       | s-        |  [4s]

     s+  =  b < 0  ?  -0x80 :  0x7f
     s-  =  b < 0  ?   0x7f : -0x80

     The cases a - b actually perform  a - (-(-b))  if B is CONST.
  */

  op[0] = simplify_gen_subreg (QImode, xop[0], mode, n_bytes-1);
  op[1] = n_bytes > 1
    ? simplify_gen_subreg (QImode, xop[0], mode, n_bytes-2)
    : NULL_RTX;

  bool need_copy = true;
  int len_call = 1 + AVR_HAVE_JMP_CALL;

  switch (code_sat)
    {
    default:
      gcc_unreachable();

    case SS_PLUS:
    case SS_MINUS:

      if (out_brvc)
        avr_asm_len ("brvc 0f", op, plen, 1);

      if (reg_overlap_mentioned_p (xop[0], xop[2]))
        {
          /* [1s,reg] */

          if (n_bytes == 1)
            avr_asm_len ("ldi %0,0x7f" CR_TAB
                         "adc %0,__zero_reg__", op, plen, 2);
          else
            avr_asm_len ("ldi %0,0x7f" CR_TAB
                         "ldi %1,0xff" CR_TAB
                         "adc %1,__zero_reg__" CR_TAB
                         "adc %0,__zero_reg__", op, plen, 4);
        }
      else if (sign == 0 && PLUS == code)
        {
          /* [1s,reg] */

          op[2] = simplify_gen_subreg (QImode, xop[2], mode, n_bytes-1);

          if (n_bytes == 1)
            avr_asm_len ("ldi %0,0x80" CR_TAB
                         "sbrs %2,7"   CR_TAB
                         "dec %0", op, plen, 3);
          else
            avr_asm_len ("ldi %0,0x80" CR_TAB
                         "cp %2,%0"    CR_TAB
                         "sbc %1,%1"   CR_TAB
                         "sbci %0,0", op, plen, 4);
        }
      else if (sign == 0 && MINUS == code)
        {
          /* [3s,reg] */

          op[2] = simplify_gen_subreg (QImode, xop[2], mode, n_bytes-1);

          if (n_bytes == 1)
            avr_asm_len ("ldi %0,0x7f" CR_TAB
                         "sbrs %2,7"   CR_TAB
                         "inc %0", op, plen, 3);
          else
            avr_asm_len ("ldi %0,0x7f" CR_TAB
                         "cp %0,%2"    CR_TAB
                         "sbc %1,%1"   CR_TAB
                         "sbci %0,-1", op, plen, 4);
        }
      else if ((sign < 0) ^ (SS_MINUS == code_sat))
        {
          /* [1s,const,B < 0] [2s,B < 0] */
          /* [3s,const,B > 0] [4s,B > 0] */

          if (n_bytes == 8)
            {
              avr_asm_len ("%~call __clr_8", op, plen, len_call);
              need_copy = false;
            }

          avr_asm_len ("ldi %0,0x80", op, plen, 1);
          if (n_bytes > 1 && need_copy)
            avr_asm_len ("clr %1", op, plen, 1);
        }
      else if ((sign > 0) ^ (SS_MINUS == code_sat))
        {
          /* [1s,const,B > 0] [2s,B > 0] */
          /* [3s,const,B < 0] [4s,B < 0] */

          if (n_bytes == 8)
            {
              avr_asm_len ("sec" CR_TAB
                           "%~call __sbc_8", op, plen, 1 + len_call);
              need_copy = false;
            }

          avr_asm_len ("ldi %0,0x7f", op, plen, 1);
          if (n_bytes > 1 && need_copy)
            avr_asm_len ("ldi %1,0xff", op, plen, 1);
        }
      else
        gcc_unreachable();

      break;

    case US_PLUS:
      /* [1u] : [2u] */

      avr_asm_len (PLUS == code ? "brcc 0f" : "brcs 0f", op, plen, 1);

      if (n_bytes == 8)
        {
          if (MINUS == code)
            avr_asm_len ("sec", op, plen, 1);
          avr_asm_len ("%~call __sbc_8", op, plen, len_call);

          need_copy = false;
        }
      else
        {
          if (MINUS == code && !test_hard_reg_class (LD_REGS, op[0]))
            avr_asm_len ("sec" CR_TAB "sbc %0,%0", op, plen, 2);
          else
            avr_asm_len (PLUS == code ? "sbc %0,%0" : "ldi %0,0xff",
                         op, plen, 1);
        }
      break; /* US_PLUS */

    case US_MINUS:
      /* [4u] : [3u] */

      avr_asm_len (PLUS == code ? "brcs 0f" : "brcc 0f", op, plen, 1);

      if (n_bytes == 8)
        {
          avr_asm_len ("%~call __clr_8", op, plen, len_call);
          need_copy = false;
        }
      else
        avr_asm_len ("clr %0", op, plen, 1);

      break;
    }

  /* We set the MSB in the unsigned case and the 2 MSBs in the signed case.
     Now copy the right value to the LSBs.  */

  if (need_copy && n_bytes > 1)
    {
      if (US_MINUS == code_sat || US_PLUS == code_sat)
        {
          avr_asm_len ("mov %1,%0", op, plen, 1);

          if (n_bytes > 2)
            {
              op[0] = xop[0];
              if (AVR_HAVE_MOVW)
                avr_asm_len ("movw %0,%1", op, plen, 1);
              else
                avr_asm_len ("mov %A0,%1" CR_TAB
                             "mov %B0,%1", op, plen, 2);
            }
        }
      else if (n_bytes > 2)
        {
          op[0] = xop[0];
          avr_asm_len ("mov %A0,%1" CR_TAB
                       "mov %B0,%1", op, plen, 2);
        }
    }

  if (need_copy && n_bytes == 8)
    {
      if (AVR_HAVE_MOVW)
        avr_asm_len ("movw %r0+2,%0" CR_TAB
                     "movw %r0+4,%0", xop, plen, 2);
      else
        avr_asm_len ("mov %r0+2,%0" CR_TAB
                     "mov %r0+3,%0" CR_TAB
                     "mov %r0+4,%0" CR_TAB
                     "mov %r0+5,%0", xop, plen, 4);
    }

  if (out_label)
    avr_asm_len ("0:", op, plen, 0);
}


/* Output addition/subtraction of register XOP[0] and a constant XOP[2] that
   is ont a compile-time constant:

      XOP[0] = XOP[0] +/- XOP[2]

   This is a helper for the function below.  The only insns that need this
   are additions/subtraction for pointer modes, i.e. HImode and PSImode.  */

static const char*
avr_out_plus_symbol (rtx *xop, enum rtx_code code, int *plen, int *pcc)
{
  enum machine_mode mode = GET_MODE (xop[0]);

  /* Only pointer modes want to add symbols.  */

  gcc_assert (mode == HImode || mode == PSImode);

  *pcc = MINUS == code ? (int) CC_SET_CZN : (int) CC_SET_N;

  avr_asm_len (PLUS == code
               ? "subi %A0,lo8(-(%2))" CR_TAB "sbci %B0,hi8(-(%2))"
               : "subi %A0,lo8(%2)"    CR_TAB "sbci %B0,hi8(%2)",
               xop, plen, -2);

  if (PSImode == mode)
    avr_asm_len (PLUS == code
                 ? "sbci %C0,hlo8(-(%2))"
                 : "sbci %C0,hlo8(%2)", xop, plen, 1);
  return "";
}


/* Prepare operands of addition/subtraction to be used with avr_out_plus_1.

   INSN is a single_set insn or an insn pattern with a binary operation as
   SET_SRC that is one of: PLUS, SS_PLUS, US_PLUS, MINUS, SS_MINUS, US_MINUS.

   XOP are the operands of INSN.  In the case of 64-bit operations with
   constant XOP[] has just one element:  The summand/subtrahend in XOP[0].
   The non-saturating insns up to 32 bits may or may not supply a "d" class
   scratch as XOP[3].

   If PLEN == NULL output the instructions.
   If PLEN != NULL set *PLEN to the length of the sequence in words.

   PCC is a pointer to store the instructions' effect on cc0.
   PCC may be NULL.

   PLEN and PCC default to NULL.

   OUT_LABEL defaults to TRUE.  For a description, see AVR_OUT_PLUS_1.

   Return ""  */

const char*
avr_out_plus (rtx insn, rtx *xop, int *plen, int *pcc, bool out_label)
{
  int cc_plus, cc_minus, cc_dummy;
  int len_plus, len_minus;
  rtx op[4];
  rtx xpattern = INSN_P (insn) ? single_set (insn) : insn;
  rtx xdest = SET_DEST (xpattern);
  enum machine_mode mode = GET_MODE (xdest);
  enum machine_mode imode = int_mode_for_mode (mode);
  int n_bytes = GET_MODE_SIZE (mode);
  enum rtx_code code_sat = GET_CODE (SET_SRC (xpattern));
  enum rtx_code code
    = (PLUS == code_sat || SS_PLUS == code_sat || US_PLUS == code_sat
       ? PLUS : MINUS);

  if (!pcc)
    pcc = &cc_dummy;

  /* PLUS and MINUS don't saturate:  Use modular wrap-around.  */

  if (PLUS == code_sat || MINUS == code_sat)
    code_sat = UNKNOWN;

  if (n_bytes <= 4 && REG_P (xop[2]))
    {
      avr_out_plus_1 (xop, plen, code, pcc, code_sat, 0, out_label);
      return "";
    }

  if (8 == n_bytes)
    {
      op[0] = gen_rtx_REG (DImode, ACC_A);
      op[1] = gen_rtx_REG (DImode, ACC_A);
      op[2] = avr_to_int_mode (xop[0]);
    }
  else
    {
      if (!REG_P (xop[2])
          && !CONST_INT_P (xop[2])
          && !CONST_FIXED_P (xop[2]))
        {
          return avr_out_plus_symbol (xop, code, plen, pcc);
        }

      op[0] = avr_to_int_mode (xop[0]);
      op[1] = avr_to_int_mode (xop[1]);
      op[2] = avr_to_int_mode (xop[2]);
    }

  /* Saturations and 64-bit operations don't have a clobber operand.
     For the other cases, the caller will provide a proper XOP[3].  */

  xpattern = INSN_P (insn) ? PATTERN (insn) : insn;
  op[3] = PARALLEL == GET_CODE (xpattern) ? xop[3] : NULL_RTX;

  /* Saturation will need the sign of the original operand.  */

  rtx xmsb = simplify_gen_subreg (QImode, op[2], imode, n_bytes-1);
  int sign = INTVAL (xmsb) < 0 ? -1 : 1;

  /* If we subtract and the subtrahend is a constant, then negate it
     so that avr_out_plus_1 can be used.  */

  if (MINUS == code)
    op[2] = simplify_unary_operation (NEG, imode, op[2], imode);

  /* Work out the shortest sequence.  */

  avr_out_plus_1 (op, &len_minus, MINUS, &cc_minus, code_sat, sign, out_label);
  avr_out_plus_1 (op, &len_plus, PLUS, &cc_plus, code_sat, sign, out_label);

  if (plen)
    {
      *plen = (len_minus <= len_plus) ? len_minus : len_plus;
      *pcc  = (len_minus <= len_plus) ? cc_minus : cc_plus;
    }
  else if (len_minus <= len_plus)
    avr_out_plus_1 (op, NULL, MINUS, pcc, code_sat, sign, out_label);
  else
    avr_out_plus_1 (op, NULL, PLUS, pcc, code_sat, sign, out_label);

  return "";
}


/* Output bit operation (IOR, AND, XOR) with register XOP[0] and compile
   time constant XOP[2]:

      XOP[0] = XOP[0] <op> XOP[2]

   and return "".  If PLEN == NULL, print assembler instructions to perform the
   operation; otherwise, set *PLEN to the length of the instruction sequence
   (in words) printed with PLEN == NULL.  XOP[3] is either an 8-bit clobber
   register or SCRATCH if no clobber register is needed for the operation.
   INSN is an INSN_P or a pattern of an insn.  */

const char*
avr_out_bitop (rtx insn, rtx *xop, int *plen)
{
  /* CODE and MODE of the operation.  */
  rtx xpattern = INSN_P (insn) ? single_set (insn) : insn;
  enum rtx_code code = GET_CODE (SET_SRC (xpattern));
  enum machine_mode mode = GET_MODE (xop[0]);

  /* Number of bytes to operate on.  */
  int i, n_bytes = GET_MODE_SIZE (mode);

  /* Value of T-flag (0 or 1) or -1 if unknow.  */
  int set_t = -1;

  /* Value (0..0xff) held in clobber register op[3] or -1 if unknown.  */
  int clobber_val = -1;

  /* op[0]: 8-bit destination register
     op[1]: 8-bit const int
     op[2]: 8-bit clobber register or SCRATCH
     op[3]: 8-bit register containing 0xff or NULL_RTX  */
  rtx op[4];

  op[2] = xop[3];
  op[3] = NULL_RTX;

  if (plen)
    *plen = 0;

  for (i = 0; i < n_bytes; i++)
    {
      /* We operate byte-wise on the destination.  */
      rtx reg8 = simplify_gen_subreg (QImode, xop[0], mode, i);
      rtx xval8 = simplify_gen_subreg (QImode, xop[2], mode, i);

      /* 8-bit value to operate with this byte. */
      unsigned int val8 = UINTVAL (xval8) & GET_MODE_MASK (QImode);

      /* Number of bits set in the current byte of the constant.  */
      int pop8 = avr_popcount (val8);

      /* Registers R16..R31 can operate with immediate.  */
      bool ld_reg_p = test_hard_reg_class (LD_REGS, reg8);

      op[0] = reg8;
      op[1] = GEN_INT (val8);

      switch (code)
        {
        case IOR:

          if (0 == pop8)
            continue;
          else if (ld_reg_p)
            avr_asm_len ("ori %0,%1", op, plen, 1);
          else if (1 == pop8)
            {
              if (set_t != 1)
                avr_asm_len ("set", op, plen, 1);
              set_t = 1;

              op[1] = GEN_INT (exact_log2 (val8));
              avr_asm_len ("bld %0,%1", op, plen, 1);
            }
          else if (8 == pop8)
            {
              if (op[3] != NULL_RTX)
                avr_asm_len ("mov %0,%3", op, plen, 1);
              else
                avr_asm_len ("clr %0" CR_TAB
                             "dec %0", op, plen, 2);

              op[3] = op[0];
            }
          else
            {
              if (clobber_val != (int) val8)
                avr_asm_len ("ldi %2,%1", op, plen, 1);
              clobber_val = (int) val8;

              avr_asm_len ("or %0,%2", op, plen, 1);
            }

          continue; /* IOR */

        case AND:

          if (8 == pop8)
            continue;
          else if (0 == pop8)
            avr_asm_len ("clr %0", op, plen, 1);
          else if (ld_reg_p)
            avr_asm_len ("andi %0,%1", op, plen, 1);
          else if (7 == pop8)
            {
              if (set_t != 0)
                avr_asm_len ("clt", op, plen, 1);
              set_t = 0;

              op[1] = GEN_INT (exact_log2 (GET_MODE_MASK (QImode) & ~val8));
              avr_asm_len ("bld %0,%1", op, plen, 1);
            }
          else
            {
              if (clobber_val != (int) val8)
                avr_asm_len ("ldi %2,%1", op, plen, 1);
              clobber_val = (int) val8;

              avr_asm_len ("and %0,%2", op, plen, 1);
            }

          continue; /* AND */

        case XOR:

          if (0 == pop8)
            continue;
          else if (8 == pop8)
            avr_asm_len ("com %0", op, plen, 1);
          else if (ld_reg_p && val8 == (1 << 7))
            avr_asm_len ("subi %0,%1", op, plen, 1);
          else
            {
              if (clobber_val != (int) val8)
                avr_asm_len ("ldi %2,%1", op, plen, 1);
              clobber_val = (int) val8;

              avr_asm_len ("eor %0,%2", op, plen, 1);
            }

          continue; /* XOR */

        default:
          /* Unknown rtx_code */
          gcc_unreachable();
        }
    } /* for all sub-bytes */

  return "";
}


/* PLEN == NULL: Output code to add CONST_INT OP[0] to SP.
   PLEN != NULL: Set *PLEN to the length of that sequence.
   Return "".  */

const char*
avr_out_addto_sp (rtx *op, int *plen)
{
  int pc_len = AVR_2_BYTE_PC ? 2 : 3;
  int addend = INTVAL (op[0]);

  if (plen)
    *plen = 0;

  if (addend < 0)
    {
      if (flag_verbose_asm || flag_print_asm_name)
        avr_asm_len (ASM_COMMENT_START "SP -= %n0", op, plen, 0);

      while (addend <= -pc_len)
        {
          addend += pc_len;
          avr_asm_len ("rcall .", op, plen, 1);
        }

      while (addend++ < 0)
        avr_asm_len ("push __zero_reg__", op, plen, 1);
    }
  else if (addend > 0)
    {
      if (flag_verbose_asm || flag_print_asm_name)
        avr_asm_len (ASM_COMMENT_START "SP += %0", op, plen, 0);

      while (addend-- > 0)
        avr_asm_len ("pop __tmp_reg__", op, plen, 1);
    }

  return "";
}


/* Outputs instructions needed for fixed point type conversion.
   This includes converting between any fixed point type, as well
   as converting to any integer type.  Conversion between integer
   types is not supported.

   Converting signed fractional types requires a bit shift if converting
   to or from any unsigned fractional type because the decimal place is
   shifted by 1 bit.  When the destination is a signed fractional, the sign
   is stored in either the carry or T bit.  */

const char*
avr_out_fract (rtx insn, rtx operands[], bool intsigned, int *plen)
{
  size_t i;
  rtx xop[6];
  RTX_CODE shift = UNKNOWN;
  bool sign_in_carry = false;
  bool msb_in_carry = false;
  bool lsb_in_tmp_reg = false;
  bool lsb_in_carry = false;
  bool frac_rounded = false;
  const char *code_ashift = "lsl %0";


#define MAY_CLOBBER(RR)                                                 \
  /* Shorthand used below.  */                                          \
  ((sign_bytes                                                          \
    && IN_RANGE (RR, dest.regno_msb - sign_bytes + 1, dest.regno_msb))  \
   || (offset && IN_RANGE (RR, dest.regno, dest.regno_msb))		\
   || (reg_unused_after (insn, all_regs_rtx[RR])                        \
       && !IN_RANGE (RR, dest.regno, dest.regno_msb)))

  struct
  {
    /* bytes       : Length of operand in bytes.
       ibyte       : Length of integral part in bytes.
       fbyte, fbit : Length of fractional part in bytes, bits.  */

    bool sbit;
    unsigned fbit, bytes, ibyte, fbyte;
    unsigned regno, regno_msb;
  } dest, src, *val[2] = { &dest, &src };

  if (plen)
    *plen = 0;

  /* Step 0:  Determine information on source and destination operand we
     ======   will need in the remainder.  */

  for (i = 0; i < sizeof (val) / sizeof (*val); i++)
    {
      enum machine_mode mode;

      xop[i] = operands[i];

      mode = GET_MODE (xop[i]);

      val[i]->bytes = GET_MODE_SIZE (mode);
      val[i]->regno = REGNO (xop[i]);
      val[i]->regno_msb = REGNO (xop[i]) + val[i]->bytes - 1;

      if (SCALAR_INT_MODE_P (mode))
        {
          val[i]->sbit = intsigned;
          val[i]->fbit = 0;
        }
      else if (ALL_SCALAR_FIXED_POINT_MODE_P (mode))
        {
          val[i]->sbit = SIGNED_SCALAR_FIXED_POINT_MODE_P (mode);
          val[i]->fbit = GET_MODE_FBIT (mode);
        }
      else
        fatal_insn ("unsupported fixed-point conversion", insn);

      val[i]->fbyte = (1 + val[i]->fbit) / BITS_PER_UNIT;
      val[i]->ibyte = val[i]->bytes - val[i]->fbyte;
    }

  // Byte offset of the decimal point taking into account different place
  // of the decimal point in input and output and different register numbers
  // of input and output.
  int offset = dest.regno - src.regno + dest.fbyte - src.fbyte;

  // Number of destination bytes that will come from sign / zero extension.
  int sign_bytes = (dest.ibyte - src.ibyte) * (dest.ibyte > src.ibyte);

  // Number of bytes at the low end to be filled with zeros.
  int zero_bytes = (dest.fbyte - src.fbyte) * (dest.fbyte > src.fbyte);

  // Do we have a 16-Bit register that is cleared?
  rtx clrw = NULL_RTX;

  bool sign_extend = src.sbit && sign_bytes;

  if (0 == dest.fbit % 8 && 7 == src.fbit % 8)
    shift = ASHIFT;
  else if (7 == dest.fbit % 8 && 0 == src.fbit % 8)
    shift = ASHIFTRT;
  else if (dest.fbit % 8 == src.fbit % 8)
    shift = UNKNOWN;
  else
    gcc_unreachable();

  /* If we need to round the fraction part, we might need to save/round it
     before clobbering any of it in Step 1.  Also, we might to want to do
     the rounding now to make use of LD_REGS.  */
  if (SCALAR_INT_MODE_P (GET_MODE (xop[0]))
      && SCALAR_ACCUM_MODE_P (GET_MODE (xop[1]))
      && !TARGET_FRACT_CONV_TRUNC)
    {
      bool overlap
	= (src.regno <=
	   (offset ? dest.regno_msb - sign_bytes : dest.regno + zero_bytes - 1)
	   && dest.regno - offset -1 >= dest.regno);
      unsigned s0 = dest.regno - offset -1;
      bool use_src = true;
      unsigned sn;
      unsigned copied_msb = src.regno_msb;
      bool have_carry = false;

      if (src.ibyte > dest.ibyte)
	copied_msb -= src.ibyte - dest.ibyte;

      for (sn = s0; sn <= copied_msb; sn++)
	if (!IN_RANGE (sn, dest.regno, dest.regno_msb)
	    && !reg_unused_after (insn, all_regs_rtx[sn]))
	  use_src = false;
      if (use_src && TEST_HARD_REG_BIT (reg_class_contents[LD_REGS], s0))
	{
	  avr_asm_len ("tst %0" CR_TAB "brpl 0f",
		       &all_regs_rtx[src.regno_msb], plen, 2);
	  sn = src.regno;
	  if (sn < s0)
	    {
	      if (TEST_HARD_REG_BIT (reg_class_contents[LD_REGS], sn))
		avr_asm_len ("cpi %0,1", &all_regs_rtx[sn], plen, 1);
	      else
		avr_asm_len ("sec" CR_TAB "cpc %0,__zero_reg__",
			     &all_regs_rtx[sn], plen, 2);
	      have_carry = true;
	    }
	  while (++sn < s0)
	    avr_asm_len ("cpc %0,__zero_reg__", &all_regs_rtx[sn], plen, 1);
	  avr_asm_len (have_carry ? "sbci %0,128" : "subi %0,129",
		       &all_regs_rtx[s0], plen, 1);
	  for (sn = src.regno + src.fbyte; sn <= copied_msb; sn++)
	    avr_asm_len ("sbci %0,255", &all_regs_rtx[sn], plen, 1);
	  avr_asm_len ("\n0:", NULL, plen, 0);
	  frac_rounded = true;
	}
      else if (use_src && overlap)
	{
	  avr_asm_len ("clr __tmp_reg__" CR_TAB
		       "sbrc %1,0" CR_TAB "dec __tmp_reg__", xop, plen, 1);
	  sn = src.regno;
	  if (sn < s0)
	    {
	      avr_asm_len ("add %0,__tmp_reg__", &all_regs_rtx[sn], plen, 1);
	      have_carry = true;
	    }
	  while (++sn < s0)
	    avr_asm_len ("adc %0,__tmp_reg__", &all_regs_rtx[sn], plen, 1);
	  if (have_carry)
	    avr_asm_len ("clt" CR_TAB "bld __tmp_reg__,7" CR_TAB
			 "adc %0,__tmp_reg__",
			 &all_regs_rtx[s0], plen, 1);
	  else
	    avr_asm_len ("lsr __tmp_reg" CR_TAB "add %0,__tmp_reg__",
			 &all_regs_rtx[s0], plen, 2);
	  for (sn = src.regno + src.fbyte; sn <= copied_msb; sn++)
	    avr_asm_len ("adc %0,__zero_reg__", &all_regs_rtx[sn], plen, 1);
	  frac_rounded = true;
	}
      else if (overlap)
	{
	  bool use_src
	    = (TEST_HARD_REG_BIT (reg_class_contents[LD_REGS], s0)
	       && (IN_RANGE (s0, dest.regno, dest.regno_msb)
		   || reg_unused_after (insn, all_regs_rtx[s0])));
	  xop[2] = all_regs_rtx[s0];
	  unsigned sn = src.regno;
	  if (!use_src || sn == s0)
	    avr_asm_len ("mov __tmp_reg__,%2", xop, plen, 1);
	  /* We need to consider to-be-discarded bits
	     if the value is negative.  */
	  if (sn < s0)
	    {
	      avr_asm_len ("tst %0" CR_TAB "brpl 0f",
			   &all_regs_rtx[src.regno_msb], plen, 2);
	      /* Test to-be-discarded bytes for any nozero bits.
		 ??? Could use OR or SBIW to test two registers at once.  */
	      if (sn < s0)
		avr_asm_len ("cp %0,__zero_reg__", &all_regs_rtx[sn], plen, 1);
	      while (++sn < s0)
		avr_asm_len ("cpc %0,__zero_reg__", &all_regs_rtx[sn], plen, 1);
	      /* Set bit 0 in __tmp_reg__ if any of the lower bits was set.  */
	      if (use_src)
		avr_asm_len ("breq 0f" CR_TAB
			     "ori %2,1" "\n0:\t" "mov __tmp_reg__,%2",
			     xop, plen, 3);
	      else
		avr_asm_len ("breq 0f" CR_TAB
			     "set" CR_TAB "bld __tmp_reg__,0\n0:",
			     xop, plen, 3);
	    }
	  lsb_in_tmp_reg = true;
	}
    }

  /* Step 1:  Clear bytes at the low end and copy payload bits from source
     ======   to destination.  */

  int step = offset < 0 ? 1 : -1;
  unsigned d0 = offset < 0 ? dest.regno : dest.regno_msb;

  // We cleared at least that number of registers.
  int clr_n = 0;

  for (; d0 >= dest.regno && d0 <= dest.regno_msb; d0 += step)
    {
      // Next regno of destination is needed for MOVW
      unsigned d1 = d0 + step;

      // Current and next regno of source
      signed s0 = d0 - offset;
      signed s1 = s0 + step;

      // Must current resp. next regno be CLRed?  This applies to the low
      // bytes of the destination that have no associated source bytes.
      bool clr0 = s0 < (signed) src.regno;
      bool clr1 = s1 < (signed) src.regno && d1 >= dest.regno;

      // First gather what code to emit (if any) and additional step to
      // apply if a MOVW is in use.  xop[2] is destination rtx and xop[3]
      // is the source rtx for the current loop iteration.
      const char *code = NULL;
      int stepw = 0;

      if (clr0)
        {
          if (AVR_HAVE_MOVW && clr1 && clrw)
            {
              xop[2] = all_regs_rtx[d0 & ~1];
              xop[3] = clrw;
              code = "movw %2,%3";
              stepw = step;
            }
          else
            {
              xop[2] = all_regs_rtx[d0];
              code = "clr %2";

              if (++clr_n >= 2
                  && !clrw
                  && d0 % 2 == (step > 0))
                {
                  clrw = all_regs_rtx[d0 & ~1];
                }
            }
        }
      else if (offset && s0 <= (signed) src.regno_msb)
        {
          int movw = AVR_HAVE_MOVW && offset % 2 == 0
            && d0 % 2 == (offset > 0)
            && d1 <= dest.regno_msb && d1 >= dest.regno
            && s1 <= (signed) src.regno_msb  && s1 >= (signed) src.regno;

          xop[2] = all_regs_rtx[d0 & ~movw];
          xop[3] = all_regs_rtx[s0 & ~movw];
          code = movw ? "movw %2,%3" : "mov %2,%3";
          stepw = step * movw;
        }

      if (code)
        {
          if (sign_extend && shift != ASHIFT && !sign_in_carry
              && (d0 == src.regno_msb || d0 + stepw == src.regno_msb))
            {
              /* We are going to override the sign bit.  If we sign-extend,
                 store the sign in the Carry flag.  This is not needed if
                 the destination will be ASHIFT is the remainder because
                 the ASHIFT will set Carry without extra instruction.  */

              avr_asm_len ("lsl %0", &all_regs_rtx[src.regno_msb], plen, 1);
              sign_in_carry = true;
            }

          unsigned src_msb = dest.regno_msb - sign_bytes - offset + 1;

          if (!sign_extend && shift == ASHIFTRT && !msb_in_carry
              && src.ibyte > dest.ibyte
              && (d0 == src_msb || d0 + stepw == src_msb))
            {
              /* We are going to override the MSB.  If we shift right,
                 store the MSB in the Carry flag.  This is only needed if
                 we don't sign-extend becaue with sign-extension the MSB
                 (the sign) will be produced by the sign extension.  */

              avr_asm_len ("lsr %0", &all_regs_rtx[src_msb], plen, 1);
              msb_in_carry = true;
            }

          unsigned src_lsb = dest.regno - offset -1;

          if (shift == ASHIFT && src.fbyte > dest.fbyte && !lsb_in_carry
	      && !lsb_in_tmp_reg
              && (d0 == src_lsb || d0 + stepw == src_lsb))
            {
              /* We are going to override the new LSB; store it into carry.  */

              avr_asm_len ("lsl %0", &all_regs_rtx[src_lsb], plen, 1);
              code_ashift = "rol %0";
              lsb_in_carry = true;
            }

          avr_asm_len (code, xop, plen, 1);
          d0 += stepw;
        }
    }

  /* Step 2:  Shift destination left by 1 bit position.  This might be needed
     ======   for signed input and unsigned output.  */

  if (shift == ASHIFT && src.fbyte > dest.fbyte && !lsb_in_carry)
    {
      unsigned s0 = dest.regno - offset -1;

      /* n1169 4.1.4 says:
	 "Conversions from a fixed-point to an integer type round toward zero."
	 Hence, converting a fract type to integer only gives a non-zero result
	 for -1.  */
      if (SCALAR_INT_MODE_P (GET_MODE (xop[0]))
	  && SCALAR_FRACT_MODE_P (GET_MODE (xop[1]))
	  && !TARGET_FRACT_CONV_TRUNC)
	{
	  gcc_assert (s0 == src.regno_msb);
	  /* Check if the input is -1.  We do that by checking if negating
	     the input causes an integer overflow.  */
	  unsigned sn = src.regno;
	  avr_asm_len ("cp __zero_reg__,%0", &all_regs_rtx[sn++], plen, 1);
	  while (sn <= s0)
	    avr_asm_len ("cpc __zero_reg__,%0", &all_regs_rtx[sn++], plen, 1);

	  /* Overflow goes with set carry.  Clear carry otherwise.  */
	  avr_asm_len ("brvs 0f" CR_TAB "clc\n0:", NULL, plen, 2);
	}
      /* Likewise, when converting from accumulator types to integer, we
	 need to round up negative values.  */
      else if (SCALAR_INT_MODE_P (GET_MODE (xop[0]))
	       && SCALAR_ACCUM_MODE_P (GET_MODE (xop[1]))
	       && !TARGET_FRACT_CONV_TRUNC
	       && !frac_rounded)
	{
	  bool have_carry = false;

	  xop[2] = all_regs_rtx[s0];
	  if (!lsb_in_tmp_reg && !MAY_CLOBBER (s0))
	    avr_asm_len ("mov __tmp_reg__,%2", xop, plen, 1);
	  avr_asm_len ("tst %0" CR_TAB "brpl 0f",
		       &all_regs_rtx[src.regno_msb], plen, 2);
	  if (!lsb_in_tmp_reg)
	    {
	      unsigned sn = src.regno;
	      if (sn < s0)
		{
		  avr_asm_len ("cp __zero_reg__,%0", &all_regs_rtx[sn],
			       plen, 1);
		  have_carry = true;
		}
	      while (++sn < s0)
		avr_asm_len ("cpc __zero_reg__,%0", &all_regs_rtx[sn], plen, 1);
	      lsb_in_tmp_reg = !MAY_CLOBBER (s0);
	    }
	  /* Add in C and the rounding value 127.  */
	  /* If the destination msb is a sign byte, and in LD_REGS,
	     grab it as a temporary.  */
	  if (sign_bytes
	      && TEST_HARD_REG_BIT (reg_class_contents[LD_REGS],
				    dest.regno_msb))
	    {
	      xop[3] = all_regs_rtx[dest.regno_msb];
	      avr_asm_len ("ldi %3,127", xop, plen, 1);
	      avr_asm_len ((have_carry && lsb_in_tmp_reg ? "adc __tmp_reg__,%3"
			   : have_carry ? "adc %2,%3"
			   : lsb_in_tmp_reg ? "add __tmp_reg__,%3"
			   : "add %2,%3"),
			   xop, plen, 1);
	    }
	  else
	    {
	      /* Fall back to use __zero_reg__ as a temporary.  */
	      avr_asm_len ("dec __zero_reg__", NULL, plen, 1);
	      if (have_carry)
		avr_asm_len ("clt" CR_TAB "bld __zero_reg__,7", NULL, plen, 2);
	      else
		avr_asm_len ("lsr __zero_reg__", NULL, plen, 1);
	      avr_asm_len ((have_carry && lsb_in_tmp_reg
			   ? "adc __tmp_reg__,__zero_reg__"
			   : have_carry ? "adc %2,__zero_reg__"
			   : lsb_in_tmp_reg ? "add __tmp_reg__,__zero_reg__"
			   : "add %2,__zero_reg__"),
			   xop, plen, 1);
	      avr_asm_len ("eor __zero_reg__,__zero_reg__", NULL, plen, 1);
	    }
	  for (d0 = dest.regno + zero_bytes;
	       d0 <= dest.regno_msb - sign_bytes; d0++)
	    avr_asm_len ("adc %0,__zero_reg__", &all_regs_rtx[d0], plen, 1);
	  avr_asm_len (lsb_in_tmp_reg
		       ? "\n0:\t" "lsl __tmp_reg__" : "\n0:\t" "lsl %2",
		       xop, plen, 1);
	}
      else if (MAY_CLOBBER (s0))
        avr_asm_len ("lsl %0", &all_regs_rtx[s0], plen, 1);
      else
        avr_asm_len ("mov __tmp_reg__,%0" CR_TAB
                     "lsl __tmp_reg__", &all_regs_rtx[s0], plen, 2);

      code_ashift = "rol %0";
      lsb_in_carry = true;
    }

  if (shift == ASHIFT)
    {
      for (d0 = dest.regno + zero_bytes;
           d0 <= dest.regno_msb - sign_bytes; d0++)
        {
          avr_asm_len (code_ashift, &all_regs_rtx[d0], plen, 1);
          code_ashift = "rol %0";
        }

      lsb_in_carry = false;
      sign_in_carry = true;
    }

  /* Step 4a:  Store MSB in carry if we don't already have it or will produce
     =======   it in sign-extension below.  */

  if (!sign_extend && shift == ASHIFTRT && !msb_in_carry
      && src.ibyte > dest.ibyte)
    {
      unsigned s0 = dest.regno_msb - sign_bytes - offset + 1;

      if (MAY_CLOBBER (s0))
        avr_asm_len ("lsr %0", &all_regs_rtx[s0], plen, 1);
      else
        avr_asm_len ("mov __tmp_reg__,%0" CR_TAB
                     "lsr __tmp_reg__", &all_regs_rtx[s0], plen, 2);

      msb_in_carry = true;
    }

  /* Step 3:  Sign-extend or zero-extend the destination as needed.
     ======   */

  if (sign_extend && !sign_in_carry)
    {
      unsigned s0 = src.regno_msb;

      if (MAY_CLOBBER (s0))
        avr_asm_len ("lsl %0", &all_regs_rtx[s0], plen, 1);
      else
        avr_asm_len ("mov __tmp_reg__,%0" CR_TAB
                     "lsl __tmp_reg__", &all_regs_rtx[s0], plen, 2);

      sign_in_carry = true;
  }

  gcc_assert (sign_in_carry + msb_in_carry + lsb_in_carry <= 1);

  unsigned copies = 0;
  rtx movw = sign_extend ? NULL_RTX : clrw;

  for (d0 = dest.regno_msb - sign_bytes + 1; d0 <= dest.regno_msb; d0++)
    {
      if (AVR_HAVE_MOVW && movw
          && d0 % 2 == 0 && d0 + 1 <= dest.regno_msb)
        {
          xop[2] = all_regs_rtx[d0];
          xop[3] = movw;
          avr_asm_len ("movw %2,%3", xop, plen, 1);
          d0++;
        }
      else
        {
          avr_asm_len (sign_extend ? "sbc %0,%0" : "clr %0",
                       &all_regs_rtx[d0], plen, 1);

          if (++copies >= 2 && !movw && d0 % 2 == 1)
            movw = all_regs_rtx[d0-1];
        }
    } /* for */


  /* Step 4:  Right shift the destination.  This might be needed for
     ======   conversions from unsigned to signed.  */

  if (shift == ASHIFTRT)
    {
      const char *code_ashiftrt = "lsr %0";

      if (sign_extend || msb_in_carry)
        code_ashiftrt = "ror %0";

      if (src.sbit && src.ibyte == dest.ibyte)
        code_ashiftrt = "asr %0";

      for (d0 = dest.regno_msb - sign_bytes;
           d0 >= dest.regno + zero_bytes - 1 && d0 >= dest.regno; d0--)
        {
          avr_asm_len (code_ashiftrt, &all_regs_rtx[d0], plen, 1);
          code_ashiftrt = "ror %0";
        }
    }

#undef MAY_CLOBBER

  return "";
}


/* Output fixed-point rounding.  XOP[0] = XOP[1] is the operand to round.
   XOP[2] is the rounding point, a CONST_INT.  The function prints the
   instruction sequence if PLEN = NULL and computes the length in words
   of the sequence if PLEN != NULL.  Most of this function deals with
   preparing operands for calls to `avr_out_plus' and `avr_out_bitop'.  */

const char*
avr_out_round (rtx insn ATTRIBUTE_UNUSED, rtx *xop, int *plen)
{
  enum machine_mode mode = GET_MODE (xop[0]);
  enum machine_mode imode = int_mode_for_mode (mode);
  // The smallest fractional bit not cleared by the rounding is 2^(-RP).
  int fbit = (int) GET_MODE_FBIT (mode);
  double_int i_add = double_int_zero.set_bit (fbit-1 - INTVAL (xop[2]));
  // Lengths of PLUS and AND parts.
  int len_add = 0, *plen_add = plen ? &len_add : NULL;
  int len_and = 0, *plen_and = plen ? &len_and : NULL;

  // Add-Saturate  1/2 * 2^(-RP).  Don't print the label "0:" when printing
  // the saturated addition so that we can emit the "rjmp 1f" before the
  // "0:" below.

  rtx xadd = const_fixed_from_double_int (i_add, mode);
  rtx xpattern, xsrc, op[4];

  xsrc = SIGNED_FIXED_POINT_MODE_P (mode)
    ? gen_rtx_SS_PLUS (mode, xop[1], xadd)
    : gen_rtx_US_PLUS (mode, xop[1], xadd);
  xpattern = gen_rtx_SET (VOIDmode, xop[0], xsrc);

  op[0] = xop[0];
  op[1] = xop[1];
  op[2] = xadd;
  avr_out_plus (xpattern, op, plen_add, NULL, false /* Don't print "0:" */);

  avr_asm_len ("rjmp 1f" CR_TAB
               "0:", NULL, plen_add, 1);

  // Keep  all bits from RP and higher:   ... 2^(-RP)
  // Clear all bits from RP+1 and lower:              2^(-RP-1) ...
  // Rounding point                           ^^^^^^^
  // Added above                                      ^^^^^^^^^
  rtx xreg = simplify_gen_subreg (imode, xop[0], mode, 0);
  rtx xmask = immed_double_int_const (-i_add - i_add, imode);

  xpattern = gen_rtx_SET (VOIDmode, xreg, gen_rtx_AND (imode, xreg, xmask));

  op[0] = xreg;
  op[1] = xreg;
  op[2] = xmask;
  op[3] = gen_rtx_SCRATCH (QImode);
  avr_out_bitop (xpattern, op, plen_and);
  avr_asm_len ("1:", NULL, plen, 0);

  if (plen)
    *plen = len_add + len_and;

  return "";
}


/* Create RTL split patterns for byte sized rotate expressions.  This
  produces a series of move instructions and considers overlap situations.
  Overlapping non-HImode operands need a scratch register.  */

bool
avr_rotate_bytes (rtx operands[])
{
    int i, j;
    enum machine_mode mode = GET_MODE (operands[0]);
    bool overlapped = reg_overlap_mentioned_p (operands[0], operands[1]);
    bool same_reg = rtx_equal_p (operands[0], operands[1]);
    int num = INTVAL (operands[2]);
    rtx scratch = operands[3];
    /* Work out if byte or word move is needed.  Odd byte rotates need QImode.
       Word move if no scratch is needed, otherwise use size of scratch.  */
    enum machine_mode move_mode = QImode;
    int move_size, offset, size;

    if (num & 0xf)
      move_mode = QImode;
    else if ((mode == SImode && !same_reg) || !overlapped)
      move_mode = HImode;
    else
      move_mode = GET_MODE (scratch);

    /* Force DI rotate to use QI moves since other DI moves are currently split
       into QI moves so forward propagation works better.  */
    if (mode == DImode)
      move_mode = QImode;
    /* Make scratch smaller if needed.  */
    if (SCRATCH != GET_CODE (scratch)
        && HImode == GET_MODE (scratch)
        && QImode == move_mode)
      scratch = simplify_gen_subreg (move_mode, scratch, HImode, 0);

    move_size = GET_MODE_SIZE (move_mode);
    /* Number of bytes/words to rotate.  */
    offset = (num  >> 3) / move_size;
    /* Number of moves needed.  */
    size = GET_MODE_SIZE (mode) / move_size;
    /* Himode byte swap is special case to avoid a scratch register.  */
    if (mode == HImode && same_reg)
      {
	/* HImode byte swap, using xor.  This is as quick as using scratch.  */
	rtx src, dst;
	src = simplify_gen_subreg (move_mode, operands[1], mode, 0);
	dst = simplify_gen_subreg (move_mode, operands[0], mode, 1);
	if (!rtx_equal_p (dst, src))
	  {
	     emit_move_insn (dst, gen_rtx_XOR (QImode, dst, src));
	     emit_move_insn (src, gen_rtx_XOR (QImode, src, dst));
	     emit_move_insn (dst, gen_rtx_XOR (QImode, dst, src));
	  }
      }
    else
      {
#define MAX_SIZE 8 /* GET_MODE_SIZE (DImode) / GET_MODE_SIZE (QImode)  */
	/* Create linked list of moves to determine move order.  */
	struct {
	  rtx src, dst;
	  int links;
	} move[MAX_SIZE + 8];
	int blocked, moves;

	gcc_assert (size <= MAX_SIZE);
	/* Generate list of subreg moves.  */
	for (i = 0; i < size; i++)
	  {
	    int from = i;
	    int to = (from + offset) % size;
	    move[i].src = simplify_gen_subreg (move_mode, operands[1],
						mode, from * move_size);
	    move[i].dst = simplify_gen_subreg (move_mode, operands[0],
						mode, to   * move_size);
	    move[i].links = -1;
	   }
	/* Mark dependence where a dst of one move is the src of another move.
	   The first move is a conflict as it must wait until second is
	   performed.  We ignore moves to self - we catch this later.  */
	if (overlapped)
	  for (i = 0; i < size; i++)
	    if (reg_overlap_mentioned_p (move[i].dst, operands[1]))
	      for (j = 0; j < size; j++)
		if (j != i && rtx_equal_p (move[j].src, move[i].dst))
		  {
		    /* The dst of move i is the src of move j.  */
		    move[i].links = j;
		    break;
		  }

	blocked = -1;
	moves = 0;
	/* Go through move list and perform non-conflicting moves.  As each
	   non-overlapping move is made, it may remove other conflicts
	   so the process is repeated until no conflicts remain.  */
	do
	  {
	    blocked = -1;
	    moves = 0;
	    /* Emit move where dst is not also a src or we have used that
	       src already.  */
	    for (i = 0; i < size; i++)
	      if (move[i].src != NULL_RTX)
		{
		  if (move[i].links == -1
		      || move[move[i].links].src == NULL_RTX)
		    {
		      moves++;
		      /* Ignore NOP moves to self.  */
		      if (!rtx_equal_p (move[i].dst, move[i].src))
			emit_move_insn (move[i].dst, move[i].src);

		      /* Remove  conflict from list.  */
		      move[i].src = NULL_RTX;
		    }
		  else
		    blocked = i;
		}

	    /* Check for deadlock. This is when no moves occurred and we have
	       at least one blocked move.  */
	    if (moves == 0 && blocked != -1)
	      {
		/* Need to use scratch register to break deadlock.
		   Add move to put dst of blocked move into scratch.
		   When this move occurs, it will break chain deadlock.
		   The scratch register is substituted for real move.  */

		gcc_assert (SCRATCH != GET_CODE (scratch));

		move[size].src = move[blocked].dst;
		move[size].dst =  scratch;
		/* Scratch move is never blocked.  */
		move[size].links = -1;
		/* Make sure we have valid link.  */
		gcc_assert (move[blocked].links != -1);
		/* Replace src of  blocking move with scratch reg.  */
		move[move[blocked].links].src = scratch;
		/* Make dependent on scratch move occurring.  */
		move[blocked].links = size;
		size=size+1;
	      }
	  }
	while (blocked != -1);
      }
    return true;
}


/* Worker function for `ADJUST_INSN_LENGTH'.  */
/* Modifies the length assigned to instruction INSN
   LEN is the initially computed length of the insn.  */

int
avr_adjust_insn_length (rtx insn, int len)
{
  rtx *op = recog_data.operand;
  enum attr_adjust_len adjust_len;

  /* Some complex insns don't need length adjustment and therefore
     the length need not/must not be adjusted for these insns.
     It is easier to state this in an insn attribute "adjust_len" than
     to clutter up code here...  */

  if (-1 == recog_memoized (insn))
    {
      return len;
    }

  /* Read from insn attribute "adjust_len" if/how length is to be adjusted.  */

  adjust_len = get_attr_adjust_len (insn);

  if (adjust_len == ADJUST_LEN_NO)
    {
      /* Nothing to adjust: The length from attribute "length" is fine.
         This is the default.  */

      return len;
    }

  /* Extract insn's operands.  */

  extract_constrain_insn_cached (insn);

  /* Dispatch to right function.  */

  switch (adjust_len)
    {
    case ADJUST_LEN_RELOAD_IN16: output_reload_inhi (op, op[2], &len); break;
    case ADJUST_LEN_RELOAD_IN24: avr_out_reload_inpsi (op, op[2], &len); break;
    case ADJUST_LEN_RELOAD_IN32: output_reload_insisf (op, op[2], &len); break;

    case ADJUST_LEN_OUT_BITOP: avr_out_bitop (insn, op, &len); break;

    case ADJUST_LEN_PLUS: avr_out_plus (insn, op, &len); break;
    case ADJUST_LEN_ADDTO_SP: avr_out_addto_sp (op, &len); break;

    case ADJUST_LEN_MOV8:  output_movqi (insn, op, &len); break;
    case ADJUST_LEN_MOV16: output_movhi (insn, op, &len); break;
    case ADJUST_LEN_MOV24: avr_out_movpsi (insn, op, &len); break;
    case ADJUST_LEN_MOV32: output_movsisf (insn, op, &len); break;
    case ADJUST_LEN_MOVMEM: avr_out_movmem (insn, op, &len); break;
    case ADJUST_LEN_XLOAD: avr_out_xload (insn, op, &len); break;
    case ADJUST_LEN_LPM: avr_out_lpm (insn, op, &len); break;

    case ADJUST_LEN_SFRACT: avr_out_fract (insn, op, true, &len); break;
    case ADJUST_LEN_UFRACT: avr_out_fract (insn, op, false, &len); break;
    case ADJUST_LEN_ROUND: avr_out_round (insn, op, &len); break;

    case ADJUST_LEN_TSTHI: avr_out_tsthi (insn, op, &len); break;
    case ADJUST_LEN_TSTPSI: avr_out_tstpsi (insn, op, &len); break;
    case ADJUST_LEN_TSTSI: avr_out_tstsi (insn, op, &len); break;
    case ADJUST_LEN_COMPARE: avr_out_compare (insn, op, &len); break;
    case ADJUST_LEN_COMPARE64: avr_out_compare64 (insn, op, &len); break;

    case ADJUST_LEN_LSHRQI: lshrqi3_out (insn, op, &len); break;
    case ADJUST_LEN_LSHRHI: lshrhi3_out (insn, op, &len); break;
    case ADJUST_LEN_LSHRSI: lshrsi3_out (insn, op, &len); break;

    case ADJUST_LEN_ASHRQI: ashrqi3_out (insn, op, &len); break;
    case ADJUST_LEN_ASHRHI: ashrhi3_out (insn, op, &len); break;
    case ADJUST_LEN_ASHRSI: ashrsi3_out (insn, op, &len); break;

    case ADJUST_LEN_ASHLQI: ashlqi3_out (insn, op, &len); break;
    case ADJUST_LEN_ASHLHI: ashlhi3_out (insn, op, &len); break;
    case ADJUST_LEN_ASHLSI: ashlsi3_out (insn, op, &len); break;

    case ADJUST_LEN_ASHLPSI: avr_out_ashlpsi3 (insn, op, &len); break;
    case ADJUST_LEN_ASHRPSI: avr_out_ashrpsi3 (insn, op, &len); break;
    case ADJUST_LEN_LSHRPSI: avr_out_lshrpsi3 (insn, op, &len); break;

    case ADJUST_LEN_CALL: len = AVR_HAVE_JMP_CALL ? 2 : 1; break;

    case ADJUST_LEN_INSERT_BITS: avr_out_insert_bits (op, &len); break;

    default:
      gcc_unreachable();
    }

  return len;
}

/* Return nonzero if register REG dead after INSN.  */

int
reg_unused_after (rtx insn, rtx reg)
{
  return (dead_or_set_p (insn, reg)
	  || (REG_P(reg) && _reg_unused_after (insn, reg)));
}

/* Return nonzero if REG is not used after INSN.
   We assume REG is a reload reg, and therefore does
   not live past labels.  It may live past calls or jumps though.  */

int
_reg_unused_after (rtx insn, rtx reg)
{
  enum rtx_code code;
  rtx set;

  /* If the reg is set by this instruction, then it is safe for our
     case.  Disregard the case where this is a store to memory, since
     we are checking a register used in the store address.  */
  set = single_set (insn);
  if (set && GET_CODE (SET_DEST (set)) != MEM
      && reg_overlap_mentioned_p (reg, SET_DEST (set)))
    return 1;

  while ((insn = NEXT_INSN (insn)))
    {
      rtx set;
      code = GET_CODE (insn);

#if 0
      /* If this is a label that existed before reload, then the register
	 if dead here.  However, if this is a label added by reorg, then
	 the register may still be live here.  We can't tell the difference,
	 so we just ignore labels completely.  */
      if (code == CODE_LABEL)
	return 1;
      /* else */
#endif

      if (!INSN_P (insn))
	continue;

      if (code == JUMP_INSN)
	return 0;

      /* If this is a sequence, we must handle them all at once.
	 We could have for instance a call that sets the target register,
	 and an insn in a delay slot that uses the register.  In this case,
	 we must return 0.  */
      else if (code == INSN && GET_CODE (PATTERN (insn)) == SEQUENCE)
	{
	  int i;
	  int retval = 0;

	  for (i = 0; i < XVECLEN (PATTERN (insn), 0); i++)
	    {
	      rtx this_insn = XVECEXP (PATTERN (insn), 0, i);
	      rtx set = single_set (this_insn);

	      if (CALL_P (this_insn))
		code = CALL_INSN;
	      else if (JUMP_P (this_insn))
		{
		  if (INSN_ANNULLED_BRANCH_P (this_insn))
		    return 0;
		  code = JUMP_INSN;
		}

	      if (set && reg_overlap_mentioned_p (reg, SET_SRC (set)))
		return 0;
	      if (set && reg_overlap_mentioned_p (reg, SET_DEST (set)))
		{
		  if (GET_CODE (SET_DEST (set)) != MEM)
		    retval = 1;
		  else
		    return 0;
		}
	      if (set == 0
		  && reg_overlap_mentioned_p (reg, PATTERN (this_insn)))
		return 0;
	    }
	  if (retval == 1)
	    return 1;
	  else if (code == JUMP_INSN)
	    return 0;
	}

      if (code == CALL_INSN)
	{
	  rtx tem;
	  for (tem = CALL_INSN_FUNCTION_USAGE (insn); tem; tem = XEXP (tem, 1))
	    if (GET_CODE (XEXP (tem, 0)) == USE
		&& REG_P (XEXP (XEXP (tem, 0), 0))
		&& reg_overlap_mentioned_p (reg, XEXP (XEXP (tem, 0), 0)))
	      return 0;
	  if (call_used_regs[REGNO (reg)])
	    return 1;
	}

      set = single_set (insn);

      if (set && reg_overlap_mentioned_p (reg, SET_SRC (set)))
	return 0;
      if (set && reg_overlap_mentioned_p (reg, SET_DEST (set)))
	return GET_CODE (SET_DEST (set)) != MEM;
      if (set == 0 && reg_overlap_mentioned_p (reg, PATTERN (insn)))
	return 0;
    }
  return 1;
}


/* Implement `TARGET_ASM_INTEGER'.  */
/* Target hook for assembling integer objects.  The AVR version needs
   special handling for references to certain labels.  */

static bool
avr_assemble_integer (rtx x, unsigned int size, int aligned_p)
{
  if (size == POINTER_SIZE / BITS_PER_UNIT && aligned_p
      && text_segment_operand (x, VOIDmode))
    {
      fputs ("\t.word\tgs(", asm_out_file);
      output_addr_const (asm_out_file, x);
      fputs (")\n", asm_out_file);

      return true;
    }
  else if (GET_MODE (x) == PSImode)
    {
      /* This needs binutils 2.23+, see PR binutils/13503  */

      fputs ("\t.byte\tlo8(", asm_out_file);
      output_addr_const (asm_out_file, x);
      fputs (")" ASM_COMMENT_START "need binutils PR13503\n", asm_out_file);

      fputs ("\t.byte\thi8(", asm_out_file);
      output_addr_const (asm_out_file, x);
      fputs (")" ASM_COMMENT_START "need binutils PR13503\n", asm_out_file);

      fputs ("\t.byte\thh8(", asm_out_file);
      output_addr_const (asm_out_file, x);
      fputs (")" ASM_COMMENT_START "need binutils PR13503\n", asm_out_file);

      return true;
    }
  else if (CONST_FIXED_P (x))
    {
      unsigned n;

      /* varasm fails to handle big fixed modes that don't fit in hwi.  */

      for (n = 0; n < size; n++)
        {
          rtx xn = simplify_gen_subreg (QImode, x, GET_MODE (x), n);
          default_assemble_integer (xn, 1, aligned_p);
        }

      return true;
    }

  return default_assemble_integer (x, size, aligned_p);
}


/* Implement `TARGET_CLASS_LIKELY_SPILLED_P'.  */
/* Return value is nonzero if pseudos that have been
   assigned to registers of class CLASS would likely be spilled
   because registers of CLASS are needed for spill registers.  */

static bool
avr_class_likely_spilled_p (reg_class_t c)
{
  return (c != ALL_REGS && c != ADDW_REGS);
}


/* Valid attributes:
   progmem   -  Put data to program memory.
   signal    -  Make a function to be hardware interrupt.
                After function prologue interrupts remain disabled.
   interrupt -  Make a function to be hardware interrupt. Before function
                prologue interrupts are enabled by means of SEI.
   naked     -  Don't generate function prologue/epilogue and RET
                instruction.  */

/* Handle a "progmem" attribute; arguments as in
   struct attribute_spec.handler.  */

static tree
avr_handle_progmem_attribute (tree *node, tree name,
			      tree args ATTRIBUTE_UNUSED,
			      int flags ATTRIBUTE_UNUSED,
			      bool *no_add_attrs)
{
  if (DECL_P (*node))
    {
      if (TREE_CODE (*node) == TYPE_DECL)
	{
	  /* This is really a decl attribute, not a type attribute,
	     but try to handle it for GCC 3.0 backwards compatibility.  */

	  tree type = TREE_TYPE (*node);
	  tree attr = tree_cons (name, args, TYPE_ATTRIBUTES (type));
	  tree newtype = build_type_attribute_variant (type, attr);

	  TYPE_MAIN_VARIANT (newtype) = TYPE_MAIN_VARIANT (type);
	  TREE_TYPE (*node) = newtype;
	  *no_add_attrs = true;
	}
      else if (TREE_STATIC (*node) || DECL_EXTERNAL (*node))
	{
          *no_add_attrs = false;
	}
      else
	{
	  warning (OPT_Wattributes, "%qE attribute ignored",
		   name);
	  *no_add_attrs = true;
	}
    }

  return NULL_TREE;
}

/* Handle an attribute requiring a FUNCTION_DECL; arguments as in
   struct attribute_spec.handler.  */

static tree
avr_handle_fndecl_attribute (tree *node, tree name,
			     tree args ATTRIBUTE_UNUSED,
			     int flags ATTRIBUTE_UNUSED,
			     bool *no_add_attrs)
{
  if (TREE_CODE (*node) != FUNCTION_DECL)
    {
      warning (OPT_Wattributes, "%qE attribute only applies to functions",
	       name);
      *no_add_attrs = true;
    }

  return NULL_TREE;
}

static tree
avr_handle_fntype_attribute (tree *node, tree name,
                             tree args ATTRIBUTE_UNUSED,
                             int flags ATTRIBUTE_UNUSED,
                             bool *no_add_attrs)
{
  if (TREE_CODE (*node) != FUNCTION_TYPE)
    {
      warning (OPT_Wattributes, "%qE attribute only applies to functions",
	       name);
      *no_add_attrs = true;
    }

  return NULL_TREE;
}


/* AVR attributes.  */
static const struct attribute_spec
avr_attribute_table[] =
{
  /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler,
       affects_type_identity } */
  { "progmem",   0, 0, false, false, false,  avr_handle_progmem_attribute,
    false },
  { "signal",    0, 0, true,  false, false,  avr_handle_fndecl_attribute,
    false },
  { "interrupt", 0, 0, true,  false, false,  avr_handle_fndecl_attribute,
    false },
  { "naked",     0, 0, false, true,  true,   avr_handle_fntype_attribute,
    false },
  { "OS_task",   0, 0, false, true,  true,   avr_handle_fntype_attribute,
    false },
  { "OS_main",   0, 0, false, true,  true,   avr_handle_fntype_attribute,
    false },
  { NULL,        0, 0, false, false, false, NULL, false }
};


/* Look if DECL shall be placed in program memory space by
   means of attribute `progmem' or some address-space qualifier.
   Return non-zero if DECL is data that must end up in Flash and
   zero if the data lives in RAM (.bss, .data, .rodata, ...).

   Return 2   if DECL is located in 24-bit flash address-space
   Return 1   if DECL is located in 16-bit flash address-space
   Return -1  if attribute `progmem' occurs in DECL or ATTRIBUTES
   Return 0   otherwise  */

int
avr_progmem_p (tree decl, tree attributes)
{
  tree a;

  if (TREE_CODE (decl) != VAR_DECL)
    return 0;

  if (avr_decl_memx_p (decl))
    return 2;

  if (avr_decl_flash_p (decl))
    return 1;

  if (NULL_TREE
      != lookup_attribute ("progmem", attributes))
    return -1;

  a = decl;

  do
    a = TREE_TYPE(a);
  while (TREE_CODE (a) == ARRAY_TYPE);

  if (a == error_mark_node)
    return 0;

  if (NULL_TREE != lookup_attribute ("progmem", TYPE_ATTRIBUTES (a)))
    return -1;

  return 0;
}


/* Scan type TYP for pointer references to address space ASn.
   Return ADDR_SPACE_GENERIC (i.e. 0) if all pointers targeting
   the AS are also declared to be CONST.
   Otherwise, return the respective address space, i.e. a value != 0.  */

static addr_space_t
avr_nonconst_pointer_addrspace (tree typ)
{
  while (ARRAY_TYPE == TREE_CODE (typ))
    typ = TREE_TYPE (typ);

  if (POINTER_TYPE_P (typ))
    {
      addr_space_t as;
      tree target = TREE_TYPE (typ);

      /* Pointer to function: Test the function's return type.  */

      if (FUNCTION_TYPE == TREE_CODE (target))
        return avr_nonconst_pointer_addrspace (TREE_TYPE (target));

      /* "Ordinary" pointers... */

      while (TREE_CODE (target) == ARRAY_TYPE)
        target = TREE_TYPE (target);

      /* Pointers to non-generic address space must be const.
         Refuse address spaces outside the device's flash.  */

      as = TYPE_ADDR_SPACE (target);

      if (!ADDR_SPACE_GENERIC_P (as)
          && (!TYPE_READONLY (target)
              || avr_addrspace[as].segment >= avr_current_device->n_flash))
        {
          return as;
        }

      /* Scan pointer's target type.  */

      return avr_nonconst_pointer_addrspace (target);
    }

  return ADDR_SPACE_GENERIC;
}


/* Sanity check NODE so that all pointers targeting non-generic address spaces
   go along with CONST qualifier.  Writing to these address spaces should
   be detected and complained about as early as possible.  */

static bool
avr_pgm_check_var_decl (tree node)
{
  const char *reason = NULL;

  addr_space_t as = ADDR_SPACE_GENERIC;

  gcc_assert (as == 0);

  if (avr_log.progmem)
    avr_edump ("%?: %t\n", node);

  switch (TREE_CODE (node))
    {
    default:
      break;

    case VAR_DECL:
      if (as = avr_nonconst_pointer_addrspace (TREE_TYPE (node)), as)
        reason = "variable";
      break;

    case PARM_DECL:
      if (as = avr_nonconst_pointer_addrspace (TREE_TYPE (node)), as)
        reason = "function parameter";
      break;

    case FIELD_DECL:
      if (as = avr_nonconst_pointer_addrspace (TREE_TYPE (node)), as)
        reason = "structure field";
      break;

    case FUNCTION_DECL:
      if (as = avr_nonconst_pointer_addrspace (TREE_TYPE (TREE_TYPE (node))),
          as)
        reason = "return type of function";
      break;

    case POINTER_TYPE:
      if (as = avr_nonconst_pointer_addrspace (node), as)
        reason = "pointer";
      break;
    }

  if (reason)
    {
      if (avr_addrspace[as].segment >= avr_current_device->n_flash)
        {
          if (TYPE_P (node))
            error ("%qT uses address space %qs beyond flash of %qs",
                   node, avr_addrspace[as].name, avr_current_device->name);
          else
            error ("%s %q+D uses address space %qs beyond flash of %qs",
                   reason, node, avr_addrspace[as].name,
                   avr_current_device->name);
        }
      else
        {
          if (TYPE_P (node))
            error ("pointer targeting address space %qs must be const in %qT",
                   avr_addrspace[as].name, node);
          else
            error ("pointer targeting address space %qs must be const"
                   " in %s %q+D",
                   avr_addrspace[as].name, reason, node);
        }
    }

  return reason == NULL;
}


/* Add the section attribute if the variable is in progmem.  */

static void
avr_insert_attributes (tree node, tree *attributes)
{
  avr_pgm_check_var_decl (node);

  if (TREE_CODE (node) == VAR_DECL
      && (TREE_STATIC (node) || DECL_EXTERNAL (node))
      && avr_progmem_p (node, *attributes))
    {
      addr_space_t as;
      tree node0 = node;

      /* For C++, we have to peel arrays in order to get correct
         determination of readonlyness.  */

      do
        node0 = TREE_TYPE (node0);
      while (TREE_CODE (node0) == ARRAY_TYPE);

      if (error_mark_node == node0)
        return;

      as = TYPE_ADDR_SPACE (TREE_TYPE (node));

      if (avr_addrspace[as].segment >= avr_current_device->n_flash)
        {
          error ("variable %q+D located in address space %qs"
                 " beyond flash of %qs",
                 node, avr_addrspace[as].name, avr_current_device->name);
        }

      if (!TYPE_READONLY (node0)
          && !TREE_READONLY (node))
        {
          const char *reason = "__attribute__((progmem))";

          if (!ADDR_SPACE_GENERIC_P (as))
            reason = avr_addrspace[as].name;

          if (avr_log.progmem)
            avr_edump ("\n%?: %t\n%t\n", node, node0);

          error ("variable %q+D must be const in order to be put into"
                 " read-only section by means of %qs", node, reason);
        }
    }
}


/* Implement `ASM_OUTPUT_ALIGNED_DECL_LOCAL'.  */
/* Implement `ASM_OUTPUT_ALIGNED_DECL_COMMON'.  */
/* Track need of __do_clear_bss.  */

void
avr_asm_output_aligned_decl_common (FILE * stream,
                                    const_tree decl ATTRIBUTE_UNUSED,
                                    const char *name,
                                    unsigned HOST_WIDE_INT size,
                                    unsigned int align, bool local_p)
{
  /* __gnu_lto_v1 etc. are just markers for the linker injected by toplev.c.
     There is no need to trigger __do_clear_bss code for them.  */

  if (!STR_PREFIX_P (name, "__gnu_lto"))
    avr_need_clear_bss_p = true;

  if (local_p)
    ASM_OUTPUT_ALIGNED_LOCAL (stream, name, size, align);
  else
    ASM_OUTPUT_ALIGNED_COMMON (stream, name, size, align);
}


/* Unnamed section callback for data_section
   to track need of __do_copy_data.  */

static void
avr_output_data_section_asm_op (const void *data)
{
  avr_need_copy_data_p = true;

  /* Dispatch to default.  */
  output_section_asm_op (data);
}


/* Unnamed section callback for bss_section
   to track need of __do_clear_bss.  */

static void
avr_output_bss_section_asm_op (const void *data)
{
  avr_need_clear_bss_p = true;

  /* Dispatch to default.  */
  output_section_asm_op (data);
}


/* Unnamed section callback for progmem*.data sections.  */

static void
avr_output_progmem_section_asm_op (const void *data)
{
  fprintf (asm_out_file, "\t.section\t%s,\"a\",@progbits\n",
           (const char*) data);
}


/* Implement `TARGET_ASM_INIT_SECTIONS'.  */

static void
avr_asm_init_sections (void)
{
  /* Set up a section for jump tables.  Alignment is handled by
     ASM_OUTPUT_BEFORE_CASE_LABEL.  */

  if (AVR_HAVE_JMP_CALL)
    {
      progmem_swtable_section
        = get_unnamed_section (0, output_section_asm_op,
                               "\t.section\t.progmem.gcc_sw_table"
                               ",\"a\",@progbits");
    }
  else
    {
      progmem_swtable_section
        = get_unnamed_section (SECTION_CODE, output_section_asm_op,
                               "\t.section\t.progmem.gcc_sw_table"
                               ",\"ax\",@progbits");
    }

  /* Override section callbacks to keep track of `avr_need_clear_bss_p'
     resp. `avr_need_copy_data_p'.  */

  readonly_data_section->unnamed.callback = avr_output_data_section_asm_op;
  data_section->unnamed.callback = avr_output_data_section_asm_op;
  bss_section->unnamed.callback = avr_output_bss_section_asm_op;
}


/* Implement `TARGET_ASM_FUNCTION_RODATA_SECTION'.  */

static section*
avr_asm_function_rodata_section (tree decl)
{
  /* If a function is unused and optimized out by -ffunction-sections
     and --gc-sections, ensure that the same will happen for its jump
     tables by putting them into individual sections.  */

  unsigned int flags;
  section * frodata;

  /* Get the frodata section from the default function in varasm.c
     but treat function-associated data-like jump tables as code
     rather than as user defined data.  AVR has no constant pools.  */
  {
    int fdata = flag_data_sections;

    flag_data_sections = flag_function_sections;
    frodata = default_function_rodata_section (decl);
    flag_data_sections = fdata;
    flags = frodata->common.flags;
  }

  if (frodata != readonly_data_section
      && flags & SECTION_NAMED)
    {
      /* Adjust section flags and replace section name prefix.  */

      unsigned int i;

      static const char* const prefix[] =
        {
          ".rodata",          ".progmem.gcc_sw_table",
          ".gnu.linkonce.r.", ".gnu.linkonce.t."
        };

      for (i = 0; i < sizeof (prefix) / sizeof (*prefix); i += 2)
        {
          const char * old_prefix = prefix[i];
          const char * new_prefix = prefix[i+1];
          const char * name = frodata->named.name;

          if (STR_PREFIX_P (name, old_prefix))
            {
              const char *rname = ACONCAT ((new_prefix,
                                            name + strlen (old_prefix), NULL));
              flags &= ~SECTION_CODE;
              flags |= AVR_HAVE_JMP_CALL ? 0 : SECTION_CODE;

              return get_section (rname, flags, frodata->named.decl);
            }
        }
    }

  return progmem_swtable_section;
}


/* Implement `TARGET_ASM_NAMED_SECTION'.  */
/* Track need of __do_clear_bss, __do_copy_data for named sections.  */

static void
avr_asm_named_section (const char *name, unsigned int flags, tree decl)
{
  if (flags & AVR_SECTION_PROGMEM)
    {
      addr_space_t as = (flags & AVR_SECTION_PROGMEM) / SECTION_MACH_DEP;
      const char *old_prefix = ".rodata";
      const char *new_prefix = avr_addrspace[as].section_name;

      if (STR_PREFIX_P (name, old_prefix))
        {
          const char *sname = ACONCAT ((new_prefix,
                                        name + strlen (old_prefix), NULL));
          default_elf_asm_named_section (sname, flags, decl);
          return;
        }

      default_elf_asm_named_section (new_prefix, flags, decl);
      return;
    }

  if (!avr_need_copy_data_p)
    avr_need_copy_data_p = (STR_PREFIX_P (name, ".data")
                            || STR_PREFIX_P (name, ".rodata")
                            || STR_PREFIX_P (name, ".gnu.linkonce.d"));

  if (!avr_need_clear_bss_p)
    avr_need_clear_bss_p = STR_PREFIX_P (name, ".bss");

  default_elf_asm_named_section (name, flags, decl);
}


/* Implement `TARGET_SECTION_TYPE_FLAGS'.  */

static unsigned int
avr_section_type_flags (tree decl, const char *name, int reloc)
{
  unsigned int flags = default_section_type_flags (decl, name, reloc);

  if (STR_PREFIX_P (name, ".noinit"))
    {
      if (decl && TREE_CODE (decl) == VAR_DECL
	  && DECL_INITIAL (decl) == NULL_TREE)
	flags |= SECTION_BSS;  /* @nobits */
      else
	warning (0, "only uninitialized variables can be placed in the "
		 ".noinit section");
    }

  if (decl && DECL_P (decl)
      && avr_progmem_p (decl, DECL_ATTRIBUTES (decl)))
    {
      addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (decl));

      /* Attribute progmem puts data in generic address space.
         Set section flags as if it was in __flash to get the right
         section prefix in the remainder.  */

      if (ADDR_SPACE_GENERIC_P (as))
        as = ADDR_SPACE_FLASH;

      flags |= as * SECTION_MACH_DEP;
      flags &= ~SECTION_WRITE;
      flags &= ~SECTION_BSS;
    }

  return flags;
}


/* Implement `TARGET_ENCODE_SECTION_INFO'.  */

static void
avr_encode_section_info (tree decl, rtx rtl, int new_decl_p)
{
  /* In avr_handle_progmem_attribute, DECL_INITIAL is not yet
     readily available, see PR34734.  So we postpone the warning
     about uninitialized data in program memory section until here.  */

  if (new_decl_p
      && decl && DECL_P (decl)
      && NULL_TREE == DECL_INITIAL (decl)
      && !DECL_EXTERNAL (decl)
      && avr_progmem_p (decl, DECL_ATTRIBUTES (decl)))
    {
      warning (OPT_Wuninitialized,
               "uninitialized variable %q+D put into "
               "program memory area", decl);
    }

  default_encode_section_info (decl, rtl, new_decl_p);

  if (decl && DECL_P (decl)
      && TREE_CODE (decl) != FUNCTION_DECL
      && MEM_P (rtl)
      && SYMBOL_REF == GET_CODE (XEXP (rtl, 0)))
   {
      rtx sym = XEXP (rtl, 0);
      tree type = TREE_TYPE (decl);
      if (type == error_mark_node)
	return;
      addr_space_t as = TYPE_ADDR_SPACE (type);

      /* PSTR strings are in generic space but located in flash:
         patch address space.  */

      if (-1 == avr_progmem_p (decl, DECL_ATTRIBUTES (decl)))
        as = ADDR_SPACE_FLASH;

      AVR_SYMBOL_SET_ADDR_SPACE (sym, as);
    }
}


/* Implement `TARGET_ASM_SELECT_SECTION' */

static section *
avr_asm_select_section (tree decl, int reloc, unsigned HOST_WIDE_INT align)
{
  section * sect = default_elf_select_section (decl, reloc, align);

  if (decl && DECL_P (decl)
      && avr_progmem_p (decl, DECL_ATTRIBUTES (decl)))
    {
      addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (decl));

      /* __progmem__ goes in generic space but shall be allocated to
         .progmem.data  */

      if (ADDR_SPACE_GENERIC_P (as))
        as = ADDR_SPACE_FLASH;

      if (sect->common.flags & SECTION_NAMED)
        {
          const char * name = sect->named.name;
          const char * old_prefix = ".rodata";
          const char * new_prefix = avr_addrspace[as].section_name;

          if (STR_PREFIX_P (name, old_prefix))
            {
              const char *sname = ACONCAT ((new_prefix,
                                            name + strlen (old_prefix), NULL));
              return get_section (sname, sect->common.flags, sect->named.decl);
            }
        }

      if (!progmem_section[as])
        {
          progmem_section[as]
            = get_unnamed_section (0, avr_output_progmem_section_asm_op,
                                   avr_addrspace[as].section_name);
        }

      return progmem_section[as];
    }

  return sect;
}

/* Implement `TARGET_ASM_FILE_START'.  */
/* Outputs some text at the start of each assembler file.  */

static void
avr_file_start (void)
{
  int sfr_offset = avr_current_arch->sfr_offset;

  if (avr_current_arch->asm_only)
    error ("MCU %qs supported for assembler only", avr_current_device->name);

  default_file_start ();

  /* Print I/O addresses of some SFRs used with IN and OUT.  */

  if (AVR_HAVE_SPH)
    fprintf (asm_out_file, "__SP_H__ = 0x%02x\n", avr_addr.sp_h - sfr_offset);

  fprintf (asm_out_file, "__SP_L__ = 0x%02x\n", avr_addr.sp_l - sfr_offset);
  fprintf (asm_out_file, "__SREG__ = 0x%02x\n", avr_addr.sreg - sfr_offset);
  if (AVR_HAVE_RAMPZ)
    fprintf (asm_out_file, "__RAMPZ__ = 0x%02x\n", avr_addr.rampz - sfr_offset);
  if (AVR_HAVE_RAMPY)
    fprintf (asm_out_file, "__RAMPY__ = 0x%02x\n", avr_addr.rampy - sfr_offset);
  if (AVR_HAVE_RAMPX)
    fprintf (asm_out_file, "__RAMPX__ = 0x%02x\n", avr_addr.rampx - sfr_offset);
  if (AVR_HAVE_RAMPD)
    fprintf (asm_out_file, "__RAMPD__ = 0x%02x\n", avr_addr.rampd - sfr_offset);
  if (AVR_XMEGA)
    fprintf (asm_out_file, "__CCP__ = 0x%02x\n", avr_addr.ccp - sfr_offset);
  fprintf (asm_out_file, "__tmp_reg__ = %d\n", TMP_REGNO);
  fprintf (asm_out_file, "__zero_reg__ = %d\n", ZERO_REGNO);
}


/* Implement `TARGET_ASM_FILE_END'.  */
/* Outputs to the stdio stream FILE some
   appropriate text to go at the end of an assembler file.  */

static void
avr_file_end (void)
{
  /* Output these only if there is anything in the
     .data* / .rodata* / .gnu.linkonce.* resp. .bss* or COMMON
     input section(s) - some code size can be saved by not
     linking in the initialization code from libgcc if resp.
     sections are empty, see PR18145.  */

  if (avr_need_copy_data_p)
    fputs (".global __do_copy_data\n", asm_out_file);

  if (avr_need_clear_bss_p)
    fputs (".global __do_clear_bss\n", asm_out_file);
}


/* Worker function for `ADJUST_REG_ALLOC_ORDER'.  */
/* Choose the order in which to allocate hard registers for
   pseudo-registers local to a basic block.

   Store the desired register order in the array `reg_alloc_order'.
   Element 0 should be the register to allocate first; element 1, the
   next register; and so on.  */

void
avr_adjust_reg_alloc_order (void)
{
  unsigned int i;
  static const int order_0[] =
    {
      24, 25,
      18, 19, 20, 21, 22, 23,
      30, 31,
      26, 27, 28, 29,
      17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2,
      0, 1,
      32, 33, 34, 35
  };
  static const int order_1[] =
    {
      18, 19, 20, 21, 22, 23, 24, 25,
      30, 31,
      26, 27, 28, 29,
      17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2,
      0, 1,
      32, 33, 34, 35
  };
  static const int order_2[] =
    {
      25, 24, 23, 22, 21, 20, 19, 18,
      30, 31,
      26, 27, 28, 29,
      17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2,
      1, 0,
      32, 33, 34, 35
  };

  const int *order = (TARGET_ORDER_1 ? order_1 :
		      TARGET_ORDER_2 ? order_2 :
		      order_0);
  for (i = 0; i < ARRAY_SIZE (order_0); ++i)
      reg_alloc_order[i] = order[i];
}


/* Implement `TARGET_REGISTER_MOVE_COST' */

static int
avr_register_move_cost (enum machine_mode mode ATTRIBUTE_UNUSED,
                        reg_class_t from, reg_class_t to)
{
  return (from == STACK_REG ? 6
          : to == STACK_REG ? 12
          : 2);
}


/* Implement `TARGET_MEMORY_MOVE_COST' */

static int
avr_memory_move_cost (enum machine_mode mode,
                      reg_class_t rclass ATTRIBUTE_UNUSED,
                      bool in ATTRIBUTE_UNUSED)
{
  return (mode == QImode ? 2
          : mode == HImode ? 4
          : mode == SImode ? 8
          : mode == SFmode ? 8
          : 16);
}


/* Mutually recursive subroutine of avr_rtx_cost for calculating the
   cost of an RTX operand given its context.  X is the rtx of the
   operand, MODE is its mode, and OUTER is the rtx_code of this
   operand's parent operator.  */

static int
avr_operand_rtx_cost (rtx x, enum machine_mode mode, enum rtx_code outer,
		      int opno, bool speed)
{
  enum rtx_code code = GET_CODE (x);
  int total;

  switch (code)
    {
    case REG:
    case SUBREG:
      return 0;

    case CONST_INT:
    case CONST_FIXED:
    case CONST_DOUBLE:
      return COSTS_N_INSNS (GET_MODE_SIZE (mode));

    default:
      break;
    }

  total = 0;
  avr_rtx_costs (x, code, outer, opno, &total, speed);
  return total;
}

/* Worker function for AVR backend's rtx_cost function.
   X is rtx expression whose cost is to be calculated.
   Return true if the complete cost has been computed.
   Return false if subexpressions should be scanned.
   In either case, *TOTAL contains the cost result.  */

static bool
avr_rtx_costs_1 (rtx x, int codearg, int outer_code ATTRIBUTE_UNUSED,
                 int opno ATTRIBUTE_UNUSED, int *total, bool speed)
{
  enum rtx_code code = (enum rtx_code) codearg;
  enum machine_mode mode = GET_MODE (x);
  HOST_WIDE_INT val;

  switch (code)
    {
    case CONST_INT:
    case CONST_FIXED:
    case CONST_DOUBLE:
    case SYMBOL_REF:
    case CONST:
    case LABEL_REF:
      /* Immediate constants are as cheap as registers.  */
      *total = 0;
      return true;

    case MEM:
      *total = COSTS_N_INSNS (GET_MODE_SIZE (mode));
      return true;

    case NEG:
      switch (mode)
	{
	case QImode:
	case SFmode:
	  *total = COSTS_N_INSNS (1);
	  break;

        case HImode:
        case PSImode:
        case SImode:
          *total = COSTS_N_INSNS (2 * GET_MODE_SIZE (mode) - 1);
          break;

	default:
	  return false;
	}
      *total += avr_operand_rtx_cost (XEXP (x, 0), mode, code, 0, speed);
      return true;

    case ABS:
      switch (mode)
	{
	case QImode:
	case SFmode:
	  *total = COSTS_N_INSNS (1);
	  break;

	default:
	  return false;
	}
      *total += avr_operand_rtx_cost (XEXP (x, 0), mode, code, 0, speed);
      return true;

    case NOT:
      *total = COSTS_N_INSNS (GET_MODE_SIZE (mode));
      *total += avr_operand_rtx_cost (XEXP (x, 0), mode, code, 0, speed);
      return true;

    case ZERO_EXTEND:
      *total = COSTS_N_INSNS (GET_MODE_SIZE (mode)
			      - GET_MODE_SIZE (GET_MODE (XEXP (x, 0))));
      *total += avr_operand_rtx_cost (XEXP (x, 0), mode, code, 0, speed);
      return true;

    case SIGN_EXTEND:
      *total = COSTS_N_INSNS (GET_MODE_SIZE (mode) + 2
			      - GET_MODE_SIZE (GET_MODE (XEXP (x, 0))));
      *total += avr_operand_rtx_cost (XEXP (x, 0), mode, code, 0, speed);
      return true;

    case PLUS:
      switch (mode)
	{
	case QImode:
          if (AVR_HAVE_MUL
              && MULT == GET_CODE (XEXP (x, 0))
              && register_operand (XEXP (x, 1), QImode))
            {
              /* multiply-add */
              *total = COSTS_N_INSNS (speed ? 4 : 3);
              /* multiply-add with constant: will be split and load constant. */
              if (CONST_INT_P (XEXP (XEXP (x, 0), 1)))
                *total = COSTS_N_INSNS (1) + *total;
              return true;
            }
	  *total = COSTS_N_INSNS (1);
	  if (GET_CODE (XEXP (x, 1)) != CONST_INT)
	    *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1, speed);
	  break;

	case HImode:
          if (AVR_HAVE_MUL
              && (MULT == GET_CODE (XEXP (x, 0))
                  || ASHIFT == GET_CODE (XEXP (x, 0)))
              && register_operand (XEXP (x, 1), HImode)
              && (ZERO_EXTEND == GET_CODE (XEXP (XEXP (x, 0), 0))
                  || SIGN_EXTEND == GET_CODE (XEXP (XEXP (x, 0), 0))))
            {
              /* multiply-add */
              *total = COSTS_N_INSNS (speed ? 5 : 4);
              /* multiply-add with constant: will be split and load constant. */
              if (CONST_INT_P (XEXP (XEXP (x, 0), 1)))
                *total = COSTS_N_INSNS (1) + *total;
              return true;
            }
	  if (GET_CODE (XEXP (x, 1)) != CONST_INT)
	    {
	      *total = COSTS_N_INSNS (2);
	      *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
					      speed);
	    }
	  else if (INTVAL (XEXP (x, 1)) >= -63 && INTVAL (XEXP (x, 1)) <= 63)
	    *total = COSTS_N_INSNS (1);
	  else
	    *total = COSTS_N_INSNS (2);
	  break;

        case PSImode:
          if (!CONST_INT_P (XEXP (x, 1)))
            {
              *total = COSTS_N_INSNS (3);
              *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
                                              speed);
            }
          else if (INTVAL (XEXP (x, 1)) >= -63 && INTVAL (XEXP (x, 1)) <= 63)
            *total = COSTS_N_INSNS (2);
          else
            *total = COSTS_N_INSNS (3);
          break;

	case SImode:
	  if (GET_CODE (XEXP (x, 1)) != CONST_INT)
	    {
	      *total = COSTS_N_INSNS (4);
	      *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
					      speed);
	    }
	  else if (INTVAL (XEXP (x, 1)) >= -63 && INTVAL (XEXP (x, 1)) <= 63)
	    *total = COSTS_N_INSNS (1);
	  else
	    *total = COSTS_N_INSNS (4);
	  break;

	default:
	  return false;
	}
      *total += avr_operand_rtx_cost (XEXP (x, 0), mode, code, 0, speed);
      return true;

    case MINUS:
      if (AVR_HAVE_MUL
          && QImode == mode
          && register_operand (XEXP (x, 0), QImode)
          && MULT == GET_CODE (XEXP (x, 1)))
        {
          /* multiply-sub */
          *total = COSTS_N_INSNS (speed ? 4 : 3);
          /* multiply-sub with constant: will be split and load constant. */
          if (CONST_INT_P (XEXP (XEXP (x, 1), 1)))
            *total = COSTS_N_INSNS (1) + *total;
          return true;
        }
      if (AVR_HAVE_MUL
          && HImode == mode
          && register_operand (XEXP (x, 0), HImode)
          && (MULT == GET_CODE (XEXP (x, 1))
              || ASHIFT == GET_CODE (XEXP (x, 1)))
          && (ZERO_EXTEND == GET_CODE (XEXP (XEXP (x, 1), 0))
              || SIGN_EXTEND == GET_CODE (XEXP (XEXP (x, 1), 0))))
        {
          /* multiply-sub */
          *total = COSTS_N_INSNS (speed ? 5 : 4);
          /* multiply-sub with constant: will be split and load constant. */
          if (CONST_INT_P (XEXP (XEXP (x, 1), 1)))
            *total = COSTS_N_INSNS (1) + *total;
          return true;
        }
      /* FALLTHRU */
    case AND:
    case IOR:
      *total = COSTS_N_INSNS (GET_MODE_SIZE (mode));
      *total += avr_operand_rtx_cost (XEXP (x, 0), mode, code, 0, speed);
      if (GET_CODE (XEXP (x, 1)) != CONST_INT)
	*total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1, speed);
      return true;

    case XOR:
      *total = COSTS_N_INSNS (GET_MODE_SIZE (mode));
      *total += avr_operand_rtx_cost (XEXP (x, 0), mode, code, 0, speed);
      *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1, speed);
      return true;

    case MULT:
      switch (mode)
	{
	case QImode:
	  if (AVR_HAVE_MUL)
	    *total = COSTS_N_INSNS (!speed ? 3 : 4);
	  else if (!speed)
	    *total = COSTS_N_INSNS (AVR_HAVE_JMP_CALL ? 2 : 1);
	  else
	    return false;
	  break;

	case HImode:
	  if (AVR_HAVE_MUL)
            {
              rtx op0 = XEXP (x, 0);
              rtx op1 = XEXP (x, 1);
              enum rtx_code code0 = GET_CODE (op0);
              enum rtx_code code1 = GET_CODE (op1);
              bool ex0 = SIGN_EXTEND == code0 || ZERO_EXTEND == code0;
              bool ex1 = SIGN_EXTEND == code1 || ZERO_EXTEND == code1;

              if (ex0
                  && (u8_operand (op1, HImode)
                      || s8_operand (op1, HImode)))
                {
                  *total = COSTS_N_INSNS (!speed ? 4 : 6);
                  return true;
                }
              if (ex0
                  && register_operand (op1, HImode))
                {
                  *total = COSTS_N_INSNS (!speed ? 5 : 8);
                  return true;
                }
              else if (ex0 || ex1)
                {
                  *total = COSTS_N_INSNS (!speed ? 3 : 5);
                  return true;
                }
              else if (register_operand (op0, HImode)
                       && (u8_operand (op1, HImode)
                           || s8_operand (op1, HImode)))
                {
                  *total = COSTS_N_INSNS (!speed ? 6 : 9);
                  return true;
                }
              else
                *total = COSTS_N_INSNS (!speed ? 7 : 10);
            }
	  else if (!speed)
	    *total = COSTS_N_INSNS (AVR_HAVE_JMP_CALL ? 2 : 1);
	  else
	    return false;
	  break;

        case PSImode:
          if (!speed)
            *total = COSTS_N_INSNS (AVR_HAVE_JMP_CALL ? 2 : 1);
          else
            *total = 10;
          break;

	case SImode:
	  if (AVR_HAVE_MUL)
            {
              if (!speed)
                {
                  /* Add some additional costs besides CALL like moves etc.  */

                  *total = COSTS_N_INSNS (AVR_HAVE_JMP_CALL ? 5 : 4);
                }
              else
                {
                  /* Just a rough estimate.  Even with -O2 we don't want bulky
                     code expanded inline.  */

                  *total = COSTS_N_INSNS (25);
                }
            }
          else
            {
              if (speed)
                *total = COSTS_N_INSNS (300);
              else
                /* Add some additional costs besides CALL like moves etc.  */
                *total = COSTS_N_INSNS (AVR_HAVE_JMP_CALL ? 5 : 4);
            }

          return true;

	default:
	  return false;
	}
      *total += avr_operand_rtx_cost (XEXP (x, 0), mode, code, 0, speed);
      *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1, speed);
      return true;

    case DIV:
    case MOD:
    case UDIV:
    case UMOD:
      if (!speed)
        *total = COSTS_N_INSNS (AVR_HAVE_JMP_CALL ? 2 : 1);
      else
        *total = COSTS_N_INSNS (15 * GET_MODE_SIZE (mode));
      *total += avr_operand_rtx_cost (XEXP (x, 0), mode, code, 0, speed);
      /* For div/mod with const-int divisor we have at least the cost of
         loading the divisor. */
      if (CONST_INT_P (XEXP (x, 1)))
        *total += COSTS_N_INSNS (GET_MODE_SIZE (mode));
      /* Add some overall penaly for clobbering and moving around registers */
      *total += COSTS_N_INSNS (2);
      return true;

    case ROTATE:
      switch (mode)
	{
	case QImode:
	  if (CONST_INT_P (XEXP (x, 1)) && INTVAL (XEXP (x, 1)) == 4)
	    *total = COSTS_N_INSNS (1);

	  break;

	case HImode:
	  if (CONST_INT_P (XEXP (x, 1)) && INTVAL (XEXP (x, 1)) == 8)
	    *total = COSTS_N_INSNS (3);

	  break;

	case SImode:
	  if (CONST_INT_P (XEXP (x, 1)))
	    switch (INTVAL (XEXP (x, 1)))
	      {
	      case 8:
	      case 24:
		*total = COSTS_N_INSNS (5);
		break;
	      case 16:
		*total = COSTS_N_INSNS (AVR_HAVE_MOVW ? 4 : 6);
		break;
	      }
	  break;

	default:
	  return false;
	}
      *total += avr_operand_rtx_cost (XEXP (x, 0), mode, code, 0, speed);
      return true;

    case ASHIFT:
      switch (mode)
	{
	case QImode:
	  if (GET_CODE (XEXP (x, 1)) != CONST_INT)
	    {
	      *total = COSTS_N_INSNS (!speed ? 4 : 17);
	      *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
					      speed);
	    }
	  else
	    {
	      val = INTVAL (XEXP (x, 1));
	      if (val == 7)
		*total = COSTS_N_INSNS (3);
	      else if (val >= 0 && val <= 7)
		*total = COSTS_N_INSNS (val);
	      else
		*total = COSTS_N_INSNS (1);
	    }
	  break;

	case HImode:
          if (AVR_HAVE_MUL)
            {
              if (const_2_to_7_operand (XEXP (x, 1), HImode)
                  && (SIGN_EXTEND == GET_CODE (XEXP (x, 0))
                      || ZERO_EXTEND == GET_CODE (XEXP (x, 0))))
                {
                  *total = COSTS_N_INSNS (!speed ? 4 : 6);
                  return true;
                }
            }

          if (const1_rtx == (XEXP (x, 1))
              && SIGN_EXTEND == GET_CODE (XEXP (x, 0)))
            {
              *total = COSTS_N_INSNS (2);
              return true;
            }

	  if (GET_CODE (XEXP (x, 1)) != CONST_INT)
	    {
	      *total = COSTS_N_INSNS (!speed ? 5 : 41);
	      *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
					      speed);
	    }
	  else
	    switch (INTVAL (XEXP (x, 1)))
	      {
	      case 0:
		*total = 0;
		break;
	      case 1:
	      case 8:
		*total = COSTS_N_INSNS (2);
		break;
	      case 9:
		*total = COSTS_N_INSNS (3);
		break;
	      case 2:
	      case 3:
	      case 10:
	      case 15:
		*total = COSTS_N_INSNS (4);
		break;
	      case 7:
	      case 11:
	      case 12:
		*total = COSTS_N_INSNS (5);
		break;
	      case 4:
		*total = COSTS_N_INSNS (!speed ? 5 : 8);
		break;
	      case 6:
		*total = COSTS_N_INSNS (!speed ? 5 : 9);
		break;
	      case 5:
		*total = COSTS_N_INSNS (!speed ? 5 : 10);
		break;
	      default:
	        *total = COSTS_N_INSNS (!speed ? 5 : 41);
	        *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
						speed);
	      }
	  break;

        case PSImode:
          if (!CONST_INT_P (XEXP (x, 1)))
            {
              *total = COSTS_N_INSNS (!speed ? 6 : 73);
            }
          else
            switch (INTVAL (XEXP (x, 1)))
              {
              case 0:
                *total = 0;
                break;
              case 1:
              case 8:
              case 16:
                *total = COSTS_N_INSNS (3);
                break;
              case 23:
                *total = COSTS_N_INSNS (5);
                break;
              default:
                *total = COSTS_N_INSNS (!speed ? 5 : 3 * INTVAL (XEXP (x, 1)));
                break;
              }
          break;

	case SImode:
	  if (GET_CODE (XEXP (x, 1)) != CONST_INT)
	    {
	      *total = COSTS_N_INSNS (!speed ? 7 : 113);
	      *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
					      speed);
	    }
	  else
	    switch (INTVAL (XEXP (x, 1)))
	      {
	      case 0:
		*total = 0;
		break;
	      case 24:
		*total = COSTS_N_INSNS (3);
		break;
	      case 1:
	      case 8:
	      case 16:
		*total = COSTS_N_INSNS (4);
		break;
	      case 31:
		*total = COSTS_N_INSNS (6);
		break;
	      case 2:
		*total = COSTS_N_INSNS (!speed ? 7 : 8);
		break;
	      default:
		*total = COSTS_N_INSNS (!speed ? 7 : 113);
		*total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
						speed);
	      }
	  break;

	default:
	  return false;
	}
      *total += avr_operand_rtx_cost (XEXP (x, 0), mode, code, 0, speed);
      return true;

    case ASHIFTRT:
      switch (mode)
	{
	case QImode:
	  if (GET_CODE (XEXP (x, 1)) != CONST_INT)
	    {
	      *total = COSTS_N_INSNS (!speed ? 4 : 17);
	      *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
					      speed);
	    }
	  else
	    {
	      val = INTVAL (XEXP (x, 1));
	      if (val == 6)
		*total = COSTS_N_INSNS (4);
	      else if (val == 7)
		*total = COSTS_N_INSNS (2);
	      else if (val >= 0 && val <= 7)
		*total = COSTS_N_INSNS (val);
	      else
		*total = COSTS_N_INSNS (1);
	    }
	  break;

	case HImode:
	  if (GET_CODE (XEXP (x, 1)) != CONST_INT)
	    {
	      *total = COSTS_N_INSNS (!speed ? 5 : 41);
	      *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
					      speed);
	    }
	  else
	    switch (INTVAL (XEXP (x, 1)))
	      {
	      case 0:
		*total = 0;
		break;
	      case 1:
		*total = COSTS_N_INSNS (2);
		break;
	      case 15:
		*total = COSTS_N_INSNS (3);
		break;
	      case 2:
	      case 7:
              case 8:
              case 9:
		*total = COSTS_N_INSNS (4);
		break;
              case 10:
	      case 14:
		*total = COSTS_N_INSNS (5);
		break;
              case 11:
                *total = COSTS_N_INSNS (!speed ? 5 : 6);
		break;
              case 12:
                *total = COSTS_N_INSNS (!speed ? 5 : 7);
		break;
              case 6:
	      case 13:
                *total = COSTS_N_INSNS (!speed ? 5 : 8);
		break;
	      default:
	        *total = COSTS_N_INSNS (!speed ? 5 : 41);
	        *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
						speed);
	      }
	  break;

        case PSImode:
          if (!CONST_INT_P (XEXP (x, 1)))
            {
              *total = COSTS_N_INSNS (!speed ? 6 : 73);
            }
          else
            switch (INTVAL (XEXP (x, 1)))
              {
              case 0:
                *total = 0;
                break;
              case 1:
                *total = COSTS_N_INSNS (3);
                break;
              case 16:
              case 8:
                *total = COSTS_N_INSNS (5);
                break;
              case 23:
                *total = COSTS_N_INSNS (4);
                break;
              default:
                *total = COSTS_N_INSNS (!speed ? 5 : 3 * INTVAL (XEXP (x, 1)));
                break;
              }
          break;

	case SImode:
	  if (GET_CODE (XEXP (x, 1)) != CONST_INT)
	    {
	      *total = COSTS_N_INSNS (!speed ? 7 : 113);
	      *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
					      speed);
	    }
	  else
	    switch (INTVAL (XEXP (x, 1)))
	      {
	      case 0:
		*total = 0;
		break;
	      case 1:
		*total = COSTS_N_INSNS (4);
		break;
	      case 8:
	      case 16:
	      case 24:
		*total = COSTS_N_INSNS (6);
		break;
	      case 2:
		*total = COSTS_N_INSNS (!speed ? 7 : 8);
		break;
	      case 31:
		*total = COSTS_N_INSNS (AVR_HAVE_MOVW ? 4 : 5);
		break;
	      default:
		*total = COSTS_N_INSNS (!speed ? 7 : 113);
		*total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
						speed);
	      }
	  break;

	default:
	  return false;
	}
      *total += avr_operand_rtx_cost (XEXP (x, 0), mode, code, 0, speed);
      return true;

    case LSHIFTRT:
      switch (mode)
	{
	case QImode:
	  if (GET_CODE (XEXP (x, 1)) != CONST_INT)
	    {
	      *total = COSTS_N_INSNS (!speed ? 4 : 17);
	      *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
					      speed);
	    }
	  else
	    {
	      val = INTVAL (XEXP (x, 1));
	      if (val == 7)
		*total = COSTS_N_INSNS (3);
	      else if (val >= 0 && val <= 7)
		*total = COSTS_N_INSNS (val);
	      else
		*total = COSTS_N_INSNS (1);
	    }
	  break;

	case HImode:
	  if (GET_CODE (XEXP (x, 1)) != CONST_INT)
	    {
	      *total = COSTS_N_INSNS (!speed ? 5 : 41);
	      *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
					      speed);
	    }
	  else
	    switch (INTVAL (XEXP (x, 1)))
	      {
	      case 0:
		*total = 0;
		break;
	      case 1:
	      case 8:
		*total = COSTS_N_INSNS (2);
		break;
	      case 9:
		*total = COSTS_N_INSNS (3);
		break;
	      case 2:
	      case 10:
	      case 15:
		*total = COSTS_N_INSNS (4);
		break;
	      case 7:
              case 11:
		*total = COSTS_N_INSNS (5);
		break;
	      case 3:
	      case 12:
	      case 13:
	      case 14:
		*total = COSTS_N_INSNS (!speed ? 5 : 6);
		break;
	      case 4:
		*total = COSTS_N_INSNS (!speed ? 5 : 7);
		break;
	      case 5:
	      case 6:
		*total = COSTS_N_INSNS (!speed ? 5 : 9);
		break;
	      default:
	        *total = COSTS_N_INSNS (!speed ? 5 : 41);
	        *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
						speed);
	      }
	  break;

        case PSImode:
          if (!CONST_INT_P (XEXP (x, 1)))
            {
              *total = COSTS_N_INSNS (!speed ? 6 : 73);
            }
          else
            switch (INTVAL (XEXP (x, 1)))
              {
              case 0:
                *total = 0;
                break;
              case 1:
              case 8:
              case 16:
                *total = COSTS_N_INSNS (3);
                break;
              case 23:
                *total = COSTS_N_INSNS (5);
                break;
              default:
                *total = COSTS_N_INSNS (!speed ? 5 : 3 * INTVAL (XEXP (x, 1)));
                break;
              }
          break;

	case SImode:
	  if (GET_CODE (XEXP (x, 1)) != CONST_INT)
	    {
	      *total = COSTS_N_INSNS (!speed ? 7 : 113);
	      *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
					      speed);
	    }
	  else
	    switch (INTVAL (XEXP (x, 1)))
	      {
	      case 0:
		*total = 0;
		break;
	      case 1:
		*total = COSTS_N_INSNS (4);
		break;
	      case 2:
		*total = COSTS_N_INSNS (!speed ? 7 : 8);
		break;
	      case 8:
	      case 16:
	      case 24:
		*total = COSTS_N_INSNS (4);
		break;
	      case 31:
		*total = COSTS_N_INSNS (6);
		break;
	      default:
		*total = COSTS_N_INSNS (!speed ? 7 : 113);
		*total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1,
						speed);
	      }
	  break;

	default:
	  return false;
	}
      *total += avr_operand_rtx_cost (XEXP (x, 0), mode, code, 0, speed);
      return true;

    case COMPARE:
      switch (GET_MODE (XEXP (x, 0)))
	{
	case QImode:
	  *total = COSTS_N_INSNS (1);
	  if (GET_CODE (XEXP (x, 1)) != CONST_INT)
	    *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1, speed);
	  break;

        case HImode:
	  *total = COSTS_N_INSNS (2);
	  if (GET_CODE (XEXP (x, 1)) != CONST_INT)
            *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1, speed);
	  else if (INTVAL (XEXP (x, 1)) != 0)
	    *total += COSTS_N_INSNS (1);
          break;

        case PSImode:
          *total = COSTS_N_INSNS (3);
          if (CONST_INT_P (XEXP (x, 1)) && INTVAL (XEXP (x, 1)) != 0)
            *total += COSTS_N_INSNS (2);
          break;

        case SImode:
          *total = COSTS_N_INSNS (4);
          if (GET_CODE (XEXP (x, 1)) != CONST_INT)
            *total += avr_operand_rtx_cost (XEXP (x, 1), mode, code, 1, speed);
	  else if (INTVAL (XEXP (x, 1)) != 0)
	    *total += COSTS_N_INSNS (3);
          break;

	default:
	  return false;
	}
      *total += avr_operand_rtx_cost (XEXP (x, 0), mode, code, 0, speed);
      return true;

    case TRUNCATE:
      if (AVR_HAVE_MUL
          && LSHIFTRT == GET_CODE (XEXP (x, 0))
          && MULT == GET_CODE (XEXP (XEXP (x, 0), 0))
          && CONST_INT_P (XEXP (XEXP (x, 0), 1)))
        {
          if (QImode == mode || HImode == mode)
            {
              *total = COSTS_N_INSNS (2);
              return true;
            }
        }
      break;

    default:
      break;
    }
  return false;
}


/* Implement `TARGET_RTX_COSTS'.  */

static bool
avr_rtx_costs (rtx x, int codearg, int outer_code,
	       int opno, int *total, bool speed)
{
  bool done = avr_rtx_costs_1 (x, codearg, outer_code,
                               opno, total, speed);

  if (avr_log.rtx_costs)
    {
      avr_edump ("\n%?=%b (%s) total=%d, outer=%C:\n%r\n",
                 done, speed ? "speed" : "size", *total, outer_code, x);
    }

  return done;
}


/* Implement `TARGET_ADDRESS_COST'.  */

static int
avr_address_cost (rtx x, enum machine_mode mode ATTRIBUTE_UNUSED,
                  addr_space_t as ATTRIBUTE_UNUSED,
                  bool speed ATTRIBUTE_UNUSED)
{
  int cost = 4;

  if (GET_CODE (x) == PLUS
      && CONST_INT_P (XEXP (x, 1))
      && (REG_P (XEXP (x, 0))
          || GET_CODE (XEXP (x, 0)) == SUBREG))
    {
      if (INTVAL (XEXP (x, 1)) >= 61)
        cost = 18;
    }
  else if (CONSTANT_ADDRESS_P (x))
    {
      if (optimize > 0
          && io_address_operand (x, QImode))
        cost = 2;
    }

  if (avr_log.address_cost)
    avr_edump ("\n%?: %d = %r\n", cost, x);

  return cost;
}

/* Test for extra memory constraint 'Q'.
   It's a memory address based on Y or Z pointer with valid displacement.  */

int
extra_constraint_Q (rtx x)
{
  int ok = 0;

  if (GET_CODE (XEXP (x,0)) == PLUS
      && REG_P (XEXP (XEXP (x,0), 0))
      && GET_CODE (XEXP (XEXP (x,0), 1)) == CONST_INT
      && (INTVAL (XEXP (XEXP (x,0), 1))
	  <= MAX_LD_OFFSET (GET_MODE (x))))
    {
      rtx xx = XEXP (XEXP (x,0), 0);
      int regno = REGNO (xx);

      ok = (/* allocate pseudos */
            regno >= FIRST_PSEUDO_REGISTER
            /* strictly check */
            || regno == REG_Z || regno == REG_Y
            /* XXX frame & arg pointer checks */
            || xx == frame_pointer_rtx
            || xx == arg_pointer_rtx);

      if (avr_log.constraints)
        avr_edump ("\n%?=%d reload_completed=%d reload_in_progress=%d\n %r\n",
                   ok, reload_completed, reload_in_progress, x);
    }

  return ok;
}

/* Convert condition code CONDITION to the valid AVR condition code.  */

RTX_CODE
avr_normalize_condition (RTX_CODE condition)
{
  switch (condition)
    {
    case GT:
      return GE;
    case GTU:
      return GEU;
    case LE:
      return LT;
    case LEU:
      return LTU;
    default:
      gcc_unreachable ();
    }
}

/* Helper function for `avr_reorg'.  */

static rtx
avr_compare_pattern (rtx insn)
{
  rtx pattern = single_set (insn);

  if (pattern
      && NONJUMP_INSN_P (insn)
      && SET_DEST (pattern) == cc0_rtx
      && GET_CODE (SET_SRC (pattern)) == COMPARE)
    {
      enum machine_mode mode0 = GET_MODE (XEXP (SET_SRC (pattern), 0));
      enum machine_mode mode1 = GET_MODE (XEXP (SET_SRC (pattern), 1));

      /* The 64-bit comparisons have fixed operands ACC_A and ACC_B.
         They must not be swapped, thus skip them.  */

      if ((mode0 == VOIDmode || GET_MODE_SIZE (mode0) <= 4)
          && (mode1 == VOIDmode || GET_MODE_SIZE (mode1) <= 4))
        return pattern;
    }

  return NULL_RTX;
}

/* Helper function for `avr_reorg'.  */

/* Expansion of switch/case decision trees leads to code like

       cc0 = compare (Reg, Num)
       if (cc0 == 0)
         goto L1

       cc0 = compare (Reg, Num)
       if (cc0 > 0)
         goto L2

   The second comparison is superfluous and can be deleted.
   The second jump condition can be transformed from a
   "difficult" one to a "simple" one because "cc0 > 0" and
   "cc0 >= 0" will have the same effect here.

   This function relies on the way switch/case is being expaned
   as binary decision tree.  For example code see PR 49903.

   Return TRUE if optimization performed.
   Return FALSE if nothing changed.

   INSN1 is a comparison, i.e. avr_compare_pattern != 0.

   We don't want to do this in text peephole because it is
   tedious to work out jump offsets there and the second comparison
   might have been transormed by `avr_reorg'.

   RTL peephole won't do because peephole2 does not scan across
   basic blocks.  */

static bool
avr_reorg_remove_redundant_compare (rtx insn1)
{
  rtx comp1, ifelse1, xcond1, branch1;
  rtx comp2, ifelse2, xcond2, branch2, insn2;
  enum rtx_code code;
  rtx jump, target, cond;

  /* Look out for:  compare1 - branch1 - compare2 - branch2  */

  branch1 = next_nonnote_nondebug_insn (insn1);
  if (!branch1 || !JUMP_P (branch1))
    return false;

  insn2 = next_nonnote_nondebug_insn (branch1);
  if (!insn2 || !avr_compare_pattern (insn2))
    return false;

  branch2 = next_nonnote_nondebug_insn (insn2);
  if (!branch2 || !JUMP_P (branch2))
    return false;

  comp1 = avr_compare_pattern (insn1);
  comp2 = avr_compare_pattern (insn2);
  xcond1 = single_set (branch1);
  xcond2 = single_set (branch2);

  if (!comp1 || !comp2
      || !rtx_equal_p (comp1, comp2)
      || !xcond1 || SET_DEST (xcond1) != pc_rtx
      || !xcond2 || SET_DEST (xcond2) != pc_rtx
      || IF_THEN_ELSE != GET_CODE (SET_SRC (xcond1))
      || IF_THEN_ELSE != GET_CODE (SET_SRC (xcond2)))
    {
      return false;
    }

  comp1 = SET_SRC (comp1);
  ifelse1 = SET_SRC (xcond1);
  ifelse2 = SET_SRC (xcond2);

  /* comp<n> is COMPARE now and ifelse<n> is IF_THEN_ELSE.  */

  if (EQ != GET_CODE (XEXP (ifelse1, 0))
      || !REG_P (XEXP (comp1, 0))
      || !CONST_INT_P (XEXP (comp1, 1))
      || XEXP (ifelse1, 2) != pc_rtx
      || XEXP (ifelse2, 2) != pc_rtx
      || LABEL_REF != GET_CODE (XEXP (ifelse1, 1))
      || LABEL_REF != GET_CODE (XEXP (ifelse2, 1))
      || !COMPARISON_P (XEXP (ifelse2, 0))
      || cc0_rtx != XEXP (XEXP (ifelse1, 0), 0)
      || cc0_rtx != XEXP (XEXP (ifelse2, 0), 0)
      || const0_rtx != XEXP (XEXP (ifelse1, 0), 1)
      || const0_rtx != XEXP (XEXP (ifelse2, 0), 1))
    {
      return false;
    }

  /* We filtered the insn sequence to look like

        (set (cc0)
             (compare (reg:M N)
                      (const_int VAL)))
        (set (pc)
             (if_then_else (eq (cc0)
                               (const_int 0))
                           (label_ref L1)
                           (pc)))

        (set (cc0)
             (compare (reg:M N)
                      (const_int VAL)))
        (set (pc)
             (if_then_else (CODE (cc0)
                                 (const_int 0))
                           (label_ref L2)
                           (pc)))
  */

  code = GET_CODE (XEXP (ifelse2, 0));

  /* Map GT/GTU to GE/GEU which is easier for AVR.
     The first two instructions compare/branch on EQ
     so we may replace the difficult

        if (x == VAL)   goto L1;
        if (x > VAL)    goto L2;

     with easy

         if (x == VAL)   goto L1;
         if (x >= VAL)   goto L2;

     Similarly, replace LE/LEU by LT/LTU.  */

  switch (code)
    {
    case EQ:
    case LT:  case LTU:
    case GE:  case GEU:
      break;

    case LE:  case LEU:
    case GT:  case GTU:
      code = avr_normalize_condition (code);
      break;

    default:
      return false;
    }

  /* Wrap the branches into UNSPECs so they won't be changed or
     optimized in the remainder.  */

  target = XEXP (XEXP (ifelse1, 1), 0);
  cond = XEXP (ifelse1, 0);
  jump = emit_jump_insn_after (gen_branch_unspec (target, cond), insn1);

  JUMP_LABEL (jump) = JUMP_LABEL (branch1);

  target = XEXP (XEXP (ifelse2, 1), 0);
  cond = gen_rtx_fmt_ee (code, VOIDmode, cc0_rtx, const0_rtx);
  jump = emit_jump_insn_after (gen_branch_unspec (target, cond), insn2);

  JUMP_LABEL (jump) = JUMP_LABEL (branch2);

  /* The comparisons in insn1 and insn2 are exactly the same;
     insn2 is superfluous so delete it.  */

  delete_insn (insn2);
  delete_insn (branch1);
  delete_insn (branch2);

  return true;
}


/* Implement `TARGET_MACHINE_DEPENDENT_REORG'.  */
/* Optimize conditional jumps.  */

static void
avr_reorg (void)
{
  rtx insn = get_insns();

  for (insn = next_real_insn (insn); insn; insn = next_real_insn (insn))
    {
      rtx pattern = avr_compare_pattern (insn);

      if (!pattern)
        continue;

      if (optimize
          && avr_reorg_remove_redundant_compare (insn))
        {
          continue;
        }

      if (compare_diff_p (insn))
	{
          /* Now we work under compare insn with difficult branch.  */

          rtx next = next_real_insn (insn);
          rtx pat = PATTERN (next);

          pattern = SET_SRC (pattern);

          if (true_regnum (XEXP (pattern, 0)) >= 0
              && true_regnum (XEXP (pattern, 1)) >= 0)
            {
              rtx x = XEXP (pattern, 0);
              rtx src = SET_SRC (pat);
              rtx t = XEXP (src,0);
              PUT_CODE (t, swap_condition (GET_CODE (t)));
              XEXP (pattern, 0) = XEXP (pattern, 1);
              XEXP (pattern, 1) = x;
              INSN_CODE (next) = -1;
            }
          else if (true_regnum (XEXP (pattern, 0)) >= 0
                   && XEXP (pattern, 1) == const0_rtx)
            {
              /* This is a tst insn, we can reverse it.  */
              rtx src = SET_SRC (pat);
              rtx t = XEXP (src,0);

              PUT_CODE (t, swap_condition (GET_CODE (t)));
              XEXP (pattern, 1) = XEXP (pattern, 0);
              XEXP (pattern, 0) = const0_rtx;
              INSN_CODE (next) = -1;
              INSN_CODE (insn) = -1;
            }
          else if (true_regnum (XEXP (pattern, 0)) >= 0
                   && CONST_INT_P (XEXP (pattern, 1)))
            {
              rtx x = XEXP (pattern, 1);
              rtx src = SET_SRC (pat);
              rtx t = XEXP (src,0);
              enum machine_mode mode = GET_MODE (XEXP (pattern, 0));

              if (avr_simplify_comparison_p (mode, GET_CODE (t), x))
                {
                  XEXP (pattern, 1) = gen_int_mode (INTVAL (x) + 1, mode);
                  PUT_CODE (t, avr_normalize_condition (GET_CODE (t)));
                  INSN_CODE (next) = -1;
                  INSN_CODE (insn) = -1;
                }
            }
        }
    }
}

/* Returns register number for function return value.*/

static inline unsigned int
avr_ret_register (void)
{
  return 24;
}


/* Implement `TARGET_FUNCTION_VALUE_REGNO_P'.  */

static bool
avr_function_value_regno_p (const unsigned int regno)
{
  return (regno == avr_ret_register ());
}


/* Implement `TARGET_LIBCALL_VALUE'.  */
/* Create an RTX representing the place where a
   library function returns a value of mode MODE.  */

static rtx
avr_libcall_value (enum machine_mode mode,
		   const_rtx func ATTRIBUTE_UNUSED)
{
  int offs = GET_MODE_SIZE (mode);

  if (offs <= 4)
    offs = (offs + 1) & ~1;

  return gen_rtx_REG (mode, avr_ret_register () + 2 - offs);
}


/* Implement `TARGET_FUNCTION_VALUE'.  */
/* Create an RTX representing the place where a
   function returns a value of data type VALTYPE.  */

static rtx
avr_function_value (const_tree type,
                    const_tree fn_decl_or_type ATTRIBUTE_UNUSED,
                    bool outgoing ATTRIBUTE_UNUSED)
{
  unsigned int offs;

  if (TYPE_MODE (type) != BLKmode)
    return avr_libcall_value (TYPE_MODE (type), NULL_RTX);

  offs = int_size_in_bytes (type);
  if (offs < 2)
    offs = 2;
  if (offs > 2 && offs < GET_MODE_SIZE (SImode))
    offs = GET_MODE_SIZE (SImode);
  else if (offs > GET_MODE_SIZE (SImode) && offs < GET_MODE_SIZE (DImode))
    offs = GET_MODE_SIZE (DImode);

  return gen_rtx_REG (BLKmode, avr_ret_register () + 2 - offs);
}

int
test_hard_reg_class (enum reg_class rclass, rtx x)
{
  int regno = true_regnum (x);
  if (regno < 0)
    return 0;

  if (TEST_HARD_REG_CLASS (rclass, regno))
    return 1;

  return 0;
}


/* Helper for jump_over_one_insn_p:  Test if INSN is a 2-word instruction
   and thus is suitable to be skipped by CPSE, SBRC, etc.  */

static bool
avr_2word_insn_p (rtx insn)
{
  if ((avr_current_device->dev_attribute & AVR_ERRATA_SKIP)
      || !insn
      || 2 != get_attr_length (insn))
    {
      return false;
    }

  switch (INSN_CODE (insn))
    {
    default:
      return false;

    case CODE_FOR_movqi_insn:
    case CODE_FOR_movuqq_insn:
    case CODE_FOR_movqq_insn:
      {
        rtx set  = single_set (insn);
        rtx src  = SET_SRC (set);
        rtx dest = SET_DEST (set);

        /* Factor out LDS and STS from movqi_insn.  */

        if (MEM_P (dest)
            && (REG_P (src) || src == CONST0_RTX (GET_MODE (dest))))
          {
            return CONSTANT_ADDRESS_P (XEXP (dest, 0));
          }
        else if (REG_P (dest)
                 && MEM_P (src))
          {
            return CONSTANT_ADDRESS_P (XEXP (src, 0));
          }

        return false;
      }

    case CODE_FOR_call_insn:
    case CODE_FOR_call_value_insn:
      return true;
    }
}


int
jump_over_one_insn_p (rtx insn, rtx dest)
{
  int uid = INSN_UID (GET_CODE (dest) == LABEL_REF
		      ? XEXP (dest, 0)
		      : dest);
  int jump_addr = INSN_ADDRESSES (INSN_UID (insn));
  int dest_addr = INSN_ADDRESSES (uid);
  int jump_offset = dest_addr - jump_addr - get_attr_length (insn);

  return (jump_offset == 1
          || (jump_offset == 2
              && avr_2word_insn_p (next_active_insn (insn))));
}


/* Worker function for `HARD_REGNO_MODE_OK'.  */
/* Returns 1 if a value of mode MODE can be stored starting with hard
   register number REGNO.  On the enhanced core, anything larger than
   1 byte must start in even numbered register for "movw" to work
   (this way we don't have to check for odd registers everywhere).  */

int
avr_hard_regno_mode_ok (int regno, enum machine_mode mode)
{
  /* NOTE: 8-bit values must not be disallowed for R28 or R29.
        Disallowing QI et al. in these regs might lead to code like
            (set (subreg:QI (reg:HI 28) n) ...)
        which will result in wrong code because reload does not
        handle SUBREGs of hard regsisters like this.
        This could be fixed in reload.  However, it appears
        that fixing reload is not wanted by reload people.  */

  /* Any GENERAL_REGS register can hold 8-bit values.  */

  if (GET_MODE_SIZE (mode) == 1)
    return 1;

  /* FIXME: Ideally, the following test is not needed.
        However, it turned out that it can reduce the number
        of spill fails.  AVR and it's poor endowment with
        address registers is extreme stress test for reload.  */

  if (GET_MODE_SIZE (mode) >= 4
      && regno >= REG_X)
    return 0;

  /* All modes larger than 8 bits should start in an even register.  */

  return !(regno & 1);
}


/* Implement `HARD_REGNO_CALL_PART_CLOBBERED'.  */

int
avr_hard_regno_call_part_clobbered (unsigned regno, enum machine_mode mode)
{
  /* FIXME: This hook gets called with MODE:REGNO combinations that don't
        represent valid hard registers like, e.g. HI:29.  Returning TRUE
        for such registers can lead to performance degradation as mentioned
        in PR53595.  Thus, report invalid hard registers as FALSE.  */

  if (!avr_hard_regno_mode_ok (regno, mode))
    return 0;

  /* Return true if any of the following boundaries is crossed:
     17/18, 27/28 and 29/30.  */

  return ((regno < 18 && regno + GET_MODE_SIZE (mode) > 18)
          || (regno < REG_Y && regno + GET_MODE_SIZE (mode) > REG_Y)
          || (regno < REG_Z && regno + GET_MODE_SIZE (mode) > REG_Z));
}


/* Implement `MODE_CODE_BASE_REG_CLASS'.  */

enum reg_class
avr_mode_code_base_reg_class (enum machine_mode mode ATTRIBUTE_UNUSED,
                              addr_space_t as, RTX_CODE outer_code,
                              RTX_CODE index_code ATTRIBUTE_UNUSED)
{
  if (!ADDR_SPACE_GENERIC_P (as))
    {
      return POINTER_Z_REGS;
    }

  if (!avr_strict_X)
    return reload_completed ? BASE_POINTER_REGS : POINTER_REGS;

  return PLUS == outer_code ? BASE_POINTER_REGS : POINTER_REGS;
}


/* Implement `REGNO_MODE_CODE_OK_FOR_BASE_P'.  */

bool
avr_regno_mode_code_ok_for_base_p (int regno,
                                   enum machine_mode mode ATTRIBUTE_UNUSED,
                                   addr_space_t as ATTRIBUTE_UNUSED,
                                   RTX_CODE outer_code,
                                   RTX_CODE index_code ATTRIBUTE_UNUSED)
{
  bool ok = false;

  if (!ADDR_SPACE_GENERIC_P (as))
    {
      if (regno < FIRST_PSEUDO_REGISTER
          && regno == REG_Z)
        {
          return true;
        }

      if (reg_renumber)
        {
          regno = reg_renumber[regno];

          if (regno == REG_Z)
            {
              return true;
            }
        }

      return false;
    }

  if (regno < FIRST_PSEUDO_REGISTER
      && (regno == REG_X
          || regno == REG_Y
          || regno == REG_Z
          || regno == ARG_POINTER_REGNUM))
    {
      ok = true;
    }
  else if (reg_renumber)
    {
      regno = reg_renumber[regno];

      if (regno == REG_X
          || regno == REG_Y
          || regno == REG_Z
          || regno == ARG_POINTER_REGNUM)
        {
          ok = true;
        }
    }

  if (avr_strict_X
      && PLUS == outer_code
      && regno == REG_X)
    {
      ok = false;
    }

  return ok;
}


/* A helper for `output_reload_insisf' and `output_reload_inhi'.  */
/* Set 32-bit register OP[0] to compile-time constant OP[1].
   CLOBBER_REG is a QI clobber register or NULL_RTX.
   LEN == NULL: output instructions.
   LEN != NULL: set *LEN to the length of the instruction sequence
                (in words) printed with LEN = NULL.
   If CLEAR_P is true, OP[0] had been cleard to Zero already.
   If CLEAR_P is false, nothing is known about OP[0].

   The effect on cc0 is as follows:

   Load 0 to any register except ZERO_REG : NONE
   Load ld register with any value        : NONE
   Anything else:                         : CLOBBER  */

static void
output_reload_in_const (rtx *op, rtx clobber_reg, int *len, bool clear_p)
{
  rtx src = op[1];
  rtx dest = op[0];
  rtx xval, xdest[4];
  int ival[4];
  int clobber_val = 1234;
  bool cooked_clobber_p = false;
  bool set_p = false;
  enum machine_mode mode = GET_MODE (dest);
  int n, n_bytes = GET_MODE_SIZE (mode);

  gcc_assert (REG_P (dest)
              && CONSTANT_P (src));

  if (len)
    *len = 0;

  /* (REG:SI 14) is special: It's neither in LD_REGS nor in NO_LD_REGS
     but has some subregs that are in LD_REGS.  Use the MSB (REG:QI 17).  */

  if (REGNO (dest) < 16
      && REGNO (dest) + GET_MODE_SIZE (mode) > 16)
    {
      clobber_reg = all_regs_rtx[REGNO (dest) + n_bytes - 1];
    }

  /* We might need a clobber reg but don't have one.  Look at the value to
     be loaded more closely.  A clobber is only needed if it is a symbol
     or contains a byte that is neither 0, -1 or a power of 2.  */

  if (NULL_RTX == clobber_reg
      && !test_hard_reg_class (LD_REGS, dest)
      && (! (CONST_INT_P (src) || CONST_FIXED_P (src) || CONST_DOUBLE_P (src))
          || !avr_popcount_each_byte (src, n_bytes,
                                      (1 << 0) | (1 << 1) | (1 << 8))))
    {
      /* We have no clobber register but need one.  Cook one up.
         That's cheaper than loading from constant pool.  */

      cooked_clobber_p = true;
      clobber_reg = all_regs_rtx[REG_Z + 1];
      avr_asm_len ("mov __tmp_reg__,%0", &clobber_reg, len, 1);
    }

  /* Now start filling DEST from LSB to MSB.  */

  for (n = 0; n < n_bytes; n++)
    {
      int ldreg_p;
      bool done_byte = false;
      int j;
      rtx xop[3];

      /* Crop the n-th destination byte.  */

      xdest[n] = simplify_gen_subreg (QImode, dest, mode, n);
      ldreg_p = test_hard_reg_class (LD_REGS, xdest[n]);

      if (!CONST_INT_P (src)
          && !CONST_FIXED_P (src)
          && !CONST_DOUBLE_P (src))
        {
          static const char* const asm_code[][2] =
            {
              { "ldi %2,lo8(%1)"  CR_TAB "mov %0,%2",    "ldi %0,lo8(%1)"  },
              { "ldi %2,hi8(%1)"  CR_TAB "mov %0,%2",    "ldi %0,hi8(%1)"  },
              { "ldi %2,hlo8(%1)" CR_TAB "mov %0,%2",    "ldi %0,hlo8(%1)" },
              { "ldi %2,hhi8(%1)" CR_TAB "mov %0,%2",    "ldi %0,hhi8(%1)" }
            };

          xop[0] = xdest[n];
          xop[1] = src;
          xop[2] = clobber_reg;

          avr_asm_len (asm_code[n][ldreg_p], xop, len, ldreg_p ? 1 : 2);

          continue;
        }

      /* Crop the n-th source byte.  */

      xval = simplify_gen_subreg (QImode, src, mode, n);
      ival[n] = INTVAL (xval);

      /* Look if we can reuse the low word by means of MOVW.  */

      if (n == 2
          && n_bytes >= 4
          && AVR_HAVE_MOVW)
        {
          rtx lo16 = simplify_gen_subreg (HImode, src, mode, 0);
          rtx hi16 = simplify_gen_subreg (HImode, src, mode, 2);

          if (INTVAL (lo16) == INTVAL (hi16))
            {
              if (0 != INTVAL (lo16)
                  || !clear_p)
                {
                  avr_asm_len ("movw %C0,%A0", &op[0], len, 1);
                }

              break;
            }
        }

      /* Don't use CLR so that cc0 is set as expected.  */

      if (ival[n] == 0)
        {
          if (!clear_p)
            avr_asm_len (ldreg_p ? "ldi %0,0"
                         : ZERO_REGNO == REGNO (xdest[n]) ? "clr %0"
                         : "mov %0,__zero_reg__",
                         &xdest[n], len, 1);
          continue;
        }

      if (clobber_val == ival[n]
          && REGNO (clobber_reg) == REGNO (xdest[n]))
        {
          continue;
        }

      /* LD_REGS can use LDI to move a constant value */

      if (ldreg_p)
        {
          xop[0] = xdest[n];
          xop[1] = xval;
          avr_asm_len ("ldi %0,lo8(%1)", xop, len, 1);
          continue;
        }

      /* Try to reuse value already loaded in some lower byte. */

      for (j = 0; j < n; j++)
        if (ival[j] == ival[n])
          {
            xop[0] = xdest[n];
            xop[1] = xdest[j];

            avr_asm_len ("mov %0,%1", xop, len, 1);
            done_byte = true;
            break;
          }

      if (done_byte)
        continue;

      /* Need no clobber reg for -1: Use CLR/DEC */

      if (-1 == ival[n])
        {
          if (!clear_p)
            avr_asm_len ("clr %0", &xdest[n], len, 1);

          avr_asm_len ("dec %0", &xdest[n], len, 1);
          continue;
        }
      else if (1 == ival[n])
        {
          if (!clear_p)
            avr_asm_len ("clr %0", &xdest[n], len, 1);

          avr_asm_len ("inc %0", &xdest[n], len, 1);
          continue;
        }

      /* Use T flag or INC to manage powers of 2 if we have
         no clobber reg.  */

      if (NULL_RTX == clobber_reg
          && single_one_operand (xval, QImode))
        {
          xop[0] = xdest[n];
          xop[1] = GEN_INT (exact_log2 (ival[n] & GET_MODE_MASK (QImode)));

          gcc_assert (constm1_rtx != xop[1]);

          if (!set_p)
            {
              set_p = true;
              avr_asm_len ("set", xop, len, 1);
            }

          if (!clear_p)
            avr_asm_len ("clr %0", xop, len, 1);

          avr_asm_len ("bld %0,%1", xop, len, 1);
          continue;
        }

      /* We actually need the LD_REGS clobber reg.  */

      gcc_assert (NULL_RTX != clobber_reg);

      xop[0] = xdest[n];
      xop[1] = xval;
      xop[2] = clobber_reg;
      clobber_val = ival[n];

      avr_asm_len ("ldi %2,lo8(%1)" CR_TAB
                   "mov %0,%2", xop, len, 2);
    }

  /* If we cooked up a clobber reg above, restore it.  */

  if (cooked_clobber_p)
    {
      avr_asm_len ("mov %0,__tmp_reg__", &clobber_reg, len, 1);
    }
}


/* Reload the constant OP[1] into the HI register OP[0].
   CLOBBER_REG is a QI clobber reg needed to move vast majority of consts
   into a NO_LD_REGS register.  If CLOBBER_REG is NULL_RTX we either don't
   need a clobber reg or have to cook one up.

   PLEN == NULL: Output instructions.
   PLEN != NULL: Output nothing.  Set *PLEN to number of words occupied
                 by the insns printed.

   Return "".  */

const char*
output_reload_inhi (rtx *op, rtx clobber_reg, int *plen)
{
  output_reload_in_const (op, clobber_reg, plen, false);
  return "";
}


/* Reload a SI or SF compile time constant OP[1] into the register OP[0].
   CLOBBER_REG is a QI clobber reg needed to move vast majority of consts
   into a NO_LD_REGS register.  If CLOBBER_REG is NULL_RTX we either don't
   need a clobber reg or have to cook one up.

   LEN == NULL: Output instructions.

   LEN != NULL: Output nothing.  Set *LEN to number of words occupied
                by the insns printed.

   Return "".  */

const char *
output_reload_insisf (rtx *op, rtx clobber_reg, int *len)
{
  if (AVR_HAVE_MOVW
      && !test_hard_reg_class (LD_REGS, op[0])
      && (CONST_INT_P (op[1])
          || CONST_FIXED_P (op[1])
          || CONST_DOUBLE_P (op[1])))
    {
      int len_clr, len_noclr;

      /* In some cases it is better to clear the destination beforehand, e.g.

             CLR R2   CLR R3   MOVW R4,R2   INC R2

         is shorther than

             CLR R2   INC R2   CLR  R3      CLR R4   CLR R5

         We find it too tedious to work that out in the print function.
         Instead, we call the print function twice to get the lengths of
         both methods and use the shortest one.  */

      output_reload_in_const (op, clobber_reg, &len_clr, true);
      output_reload_in_const (op, clobber_reg, &len_noclr, false);

      if (len_noclr - len_clr == 4)
        {
          /* Default needs 4 CLR instructions: clear register beforehand.  */

          avr_asm_len ("mov %A0,__zero_reg__" CR_TAB
                       "mov %B0,__zero_reg__" CR_TAB
                       "movw %C0,%A0", &op[0], len, 3);

          output_reload_in_const (op, clobber_reg, len, true);

          if (len)
            *len += 3;

          return "";
        }
    }

  /* Default: destination not pre-cleared.  */

  output_reload_in_const (op, clobber_reg, len, false);
  return "";
}

const char*
avr_out_reload_inpsi (rtx *op, rtx clobber_reg, int *len)
{
  output_reload_in_const (op, clobber_reg, len, false);
  return "";
}


/* Worker function for `ASM_OUTPUT_ADDR_VEC_ELT'.  */

void
avr_output_addr_vec_elt (FILE *stream, int value)
{
  if (AVR_HAVE_JMP_CALL)
    fprintf (stream, "\t.word gs(.L%d)\n", value);
  else
    fprintf (stream, "\trjmp .L%d\n", value);
}


/* Implement `TARGET_HARD_REGNO_SCRATCH_OK'.  */
/* Returns true if SCRATCH are safe to be allocated as a scratch
   registers (for a define_peephole2) in the current function.  */

static bool
avr_hard_regno_scratch_ok (unsigned int regno)
{
  /* Interrupt functions can only use registers that have already been saved
     by the prologue, even if they would normally be call-clobbered.  */

  if ((cfun->machine->is_interrupt || cfun->machine->is_signal)
      && !df_regs_ever_live_p (regno))
    return false;

  /* Don't allow hard registers that might be part of the frame pointer.
     Some places in the compiler just test for [HARD_]FRAME_POINTER_REGNUM
     and don't care for a frame pointer that spans more than one register.  */

  if ((!reload_completed || frame_pointer_needed)
      && (regno == REG_Y || regno == REG_Y + 1))
    {
      return false;
    }

  return true;
}


/* Worker function for `HARD_REGNO_RENAME_OK'.  */
/* Return nonzero if register OLD_REG can be renamed to register NEW_REG.  */

int
avr_hard_regno_rename_ok (unsigned int old_reg,
			  unsigned int new_reg)
{
  /* Interrupt functions can only use registers that have already been
     saved by the prologue, even if they would normally be
     call-clobbered.  */

  if ((cfun->machine->is_interrupt || cfun->machine->is_signal)
      && !df_regs_ever_live_p (new_reg))
    return 0;

  /* Don't allow hard registers that might be part of the frame pointer.
     Some places in the compiler just test for [HARD_]FRAME_POINTER_REGNUM
     and don't care for a frame pointer that spans more than one register.  */

  if ((!reload_completed || frame_pointer_needed)
      && (old_reg == REG_Y || old_reg == REG_Y + 1
          || new_reg == REG_Y || new_reg == REG_Y + 1))
    {
      return 0;
    }

  return 1;
}

/* Output a branch that tests a single bit of a register (QI, HI, SI or DImode)
   or memory location in the I/O space (QImode only).

   Operand 0: comparison operator (must be EQ or NE, compare bit to zero).
   Operand 1: register operand to test, or CONST_INT memory address.
   Operand 2: bit number.
   Operand 3: label to jump to if the test is true.  */

const char*
avr_out_sbxx_branch (rtx insn, rtx operands[])
{
  enum rtx_code comp = GET_CODE (operands[0]);
  bool long_jump = get_attr_length (insn) >= 4;
  bool reverse = long_jump || jump_over_one_insn_p (insn, operands[3]);

  if (comp == GE)
    comp = EQ;
  else if (comp == LT)
    comp = NE;

  if (reverse)
    comp = reverse_condition (comp);

  switch (GET_CODE (operands[1]))
    {
    default:
      gcc_unreachable();

    case CONST_INT:

      if (low_io_address_operand (operands[1], QImode))
        {
          if (comp == EQ)
            output_asm_insn ("sbis %i1,%2", operands);
          else
            output_asm_insn ("sbic %i1,%2", operands);
        }
      else
        {
          output_asm_insn ("in __tmp_reg__,%i1", operands);
          if (comp == EQ)
            output_asm_insn ("sbrs __tmp_reg__,%2", operands);
          else
            output_asm_insn ("sbrc __tmp_reg__,%2", operands);
        }

      break; /* CONST_INT */

    case REG:

      if (comp == EQ)
        output_asm_insn ("sbrs %T1%T2", operands);
      else
        output_asm_insn ("sbrc %T1%T2", operands);

      break; /* REG */
    }        /* switch */

  if (long_jump)
    return ("rjmp .+4" CR_TAB
            "jmp %x3");

  if (!reverse)
    return "rjmp %x3";

  return "";
}

/* Worker function for `TARGET_ASM_CONSTRUCTOR'.  */

static void
avr_asm_out_ctor (rtx symbol, int priority)
{
  fputs ("\t.global __do_global_ctors\n", asm_out_file);
  default_ctor_section_asm_out_constructor (symbol, priority);
}


/* Worker function for `TARGET_ASM_DESTRUCTOR'.  */

static void
avr_asm_out_dtor (rtx symbol, int priority)
{
  fputs ("\t.global __do_global_dtors\n", asm_out_file);
  default_dtor_section_asm_out_destructor (symbol, priority);
}


/* Worker function for `TARGET_RETURN_IN_MEMORY'.  */

static bool
avr_return_in_memory (const_tree type, const_tree fntype ATTRIBUTE_UNUSED)
{
  if (TYPE_MODE (type) == BLKmode)
    {
      HOST_WIDE_INT size = int_size_in_bytes (type);
      return (size == -1 || size > 8);
    }
  else
    return false;
}


/* Implement `CASE_VALUES_THRESHOLD'.  */
/* Supply the default for --param case-values-threshold=0  */

static unsigned int
avr_case_values_threshold (void)
{
  /* The exact break-even point between a jump table and an if-else tree
     depends on several factors not available here like, e.g. if 8-bit
     comparisons can be used in the if-else tree or not, on the
     range of the case values, if the case value can be reused, on the
     register allocation, etc.  '7' appears to be a good choice.  */

  return 7;
}


/* Implement `TARGET_ADDR_SPACE_ADDRESS_MODE'.  */

static enum machine_mode
avr_addr_space_address_mode (addr_space_t as)
{
  return avr_addrspace[as].pointer_size == 3 ? PSImode : HImode;
}


/* Implement `TARGET_ADDR_SPACE_POINTER_MODE'.  */

static enum machine_mode
avr_addr_space_pointer_mode (addr_space_t as)
{
  return avr_addr_space_address_mode (as);
}


/* Helper for following function.  */

static bool
avr_reg_ok_for_pgm_addr (rtx reg, bool strict)
{
  gcc_assert (REG_P (reg));

  if (strict)
    {
      return REGNO (reg) == REG_Z;
    }

  /* Avoid combine to propagate hard regs.  */

  if (can_create_pseudo_p()
      && REGNO (reg) < REG_Z)
    {
      return false;
    }

  return true;
}


/* Implement `TARGET_ADDR_SPACE_LEGITIMATE_ADDRESS_P'.  */

static bool
avr_addr_space_legitimate_address_p (enum machine_mode mode, rtx x,
                                     bool strict, addr_space_t as)
{
  bool ok = false;

  switch (as)
    {
    default:
      gcc_unreachable();

    case ADDR_SPACE_GENERIC:
      return avr_legitimate_address_p (mode, x, strict);

    case ADDR_SPACE_FLASH:
    case ADDR_SPACE_FLASH1:
    case ADDR_SPACE_FLASH2:
    case ADDR_SPACE_FLASH3:
    case ADDR_SPACE_FLASH4:
    case ADDR_SPACE_FLASH5:

      switch (GET_CODE (x))
        {
        case REG:
          ok = avr_reg_ok_for_pgm_addr (x, strict);
          break;

        case POST_INC:
          ok = avr_reg_ok_for_pgm_addr (XEXP (x, 0), strict);
          break;

        default:
          break;
        }

      break; /* FLASH */

    case ADDR_SPACE_MEMX:
      if (REG_P (x))
        ok = (!strict
              && can_create_pseudo_p());

      if (LO_SUM == GET_CODE (x))
        {
          rtx hi = XEXP (x, 0);
          rtx lo = XEXP (x, 1);

          ok = (REG_P (hi)
                && (!strict || REGNO (hi) < FIRST_PSEUDO_REGISTER)
                && REG_P (lo)
                && REGNO (lo) == REG_Z);
        }

      break; /* MEMX */
    }

  if (avr_log.legitimate_address_p)
    {
      avr_edump ("\n%?: ret=%b, mode=%m strict=%d "
                 "reload_completed=%d reload_in_progress=%d %s:",
                 ok, mode, strict, reload_completed, reload_in_progress,
                 reg_renumber ? "(reg_renumber)" : "");

      if (GET_CODE (x) == PLUS
          && REG_P (XEXP (x, 0))
          && CONST_INT_P (XEXP (x, 1))
          && IN_RANGE (INTVAL (XEXP (x, 1)), 0, MAX_LD_OFFSET (mode))
          && reg_renumber)
        {
          avr_edump ("(r%d ---> r%d)", REGNO (XEXP (x, 0)),
                     true_regnum (XEXP (x, 0)));
        }

      avr_edump ("\n%r\n", x);
    }

  return ok;
}


/* Implement `TARGET_ADDR_SPACE_LEGITIMIZE_ADDRESS'.  */

static rtx
avr_addr_space_legitimize_address (rtx x, rtx old_x,
                                   enum machine_mode mode, addr_space_t as)
{
  if (ADDR_SPACE_GENERIC_P (as))
    return avr_legitimize_address (x, old_x, mode);

  if (avr_log.legitimize_address)
    {
      avr_edump ("\n%?: mode=%m\n %r\n", mode, old_x);
    }

  return old_x;
}


/* Implement `TARGET_ADDR_SPACE_CONVERT'.  */

static rtx
avr_addr_space_convert (rtx src, tree type_from, tree type_to)
{
  addr_space_t as_from = TYPE_ADDR_SPACE (TREE_TYPE (type_from));
  addr_space_t as_to = TYPE_ADDR_SPACE (TREE_TYPE (type_to));

  if (avr_log.progmem)
    avr_edump ("\n%!: op = %r\nfrom = %t\nto = %t\n",
               src, type_from, type_to);

  /* Up-casting from 16-bit to 24-bit pointer.  */

  if (as_from != ADDR_SPACE_MEMX
      && as_to == ADDR_SPACE_MEMX)
    {
      int msb;
      rtx sym = src;
      rtx reg = gen_reg_rtx (PSImode);

      while (CONST == GET_CODE (sym) || PLUS == GET_CODE (sym))
        sym = XEXP (sym, 0);

      /* Look at symbol flags:  avr_encode_section_info set the flags
         also if attribute progmem was seen so that we get the right
         promotion for, e.g. PSTR-like strings that reside in generic space
         but are located in flash.  In that case we patch the incoming
         address space.  */

      if (SYMBOL_REF == GET_CODE (sym)
          && ADDR_SPACE_FLASH == AVR_SYMBOL_GET_ADDR_SPACE (sym))
        {
          as_from = ADDR_SPACE_FLASH;
        }

      /* Linearize memory: RAM has bit 23 set.  */

      msb = ADDR_SPACE_GENERIC_P (as_from)
        ? 0x80
        : avr_addrspace[as_from].segment;

      src = force_reg (Pmode, src);

      emit_insn (msb == 0
                 ? gen_zero_extendhipsi2 (reg, src)
                 : gen_n_extendhipsi2 (reg, gen_int_mode (msb, QImode), src));

      return reg;
    }

  /* Down-casting from 24-bit to 16-bit throws away the high byte.  */

  if (as_from == ADDR_SPACE_MEMX
      && as_to != ADDR_SPACE_MEMX)
    {
      rtx new_src = gen_reg_rtx (Pmode);

      src = force_reg (PSImode, src);

      emit_move_insn (new_src,
                      simplify_gen_subreg (Pmode, src, PSImode, 0));
      return new_src;
    }

  return src;
}


/* Implement `TARGET_ADDR_SPACE_SUBSET_P'.  */

static bool
avr_addr_space_subset_p (addr_space_t subset ATTRIBUTE_UNUSED,
                         addr_space_t superset ATTRIBUTE_UNUSED)
{
  /* Allow any kind of pointer mess.  */

  return true;
}


/* Implement `TARGET_CONVERT_TO_TYPE'.  */

static tree
avr_convert_to_type (tree type, tree expr)
{
  /* Print a diagnose for pointer conversion that changes the address
     space of the pointer target to a non-enclosing address space,
     provided -Waddr-space-convert is on.

     FIXME: Filter out cases where the target object is known to
            be located in the right memory, like in

                (const __flash*) PSTR ("text")

            Also try to distinguish between explicit casts requested by
            the user and implicit casts like

                void f (const __flash char*);

                void g (const char *p)
                {
                    f ((const __flash*) p);
                }

            under the assumption that an explicit casts means that the user
            knows what he is doing, e.g. interface with PSTR or old style
            code with progmem and pgm_read_xxx.
  */

  if (avr_warn_addr_space_convert
      && expr != error_mark_node
      && POINTER_TYPE_P (type)
      && POINTER_TYPE_P (TREE_TYPE (expr)))
    {
      addr_space_t as_old = TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (expr)));
      addr_space_t as_new = TYPE_ADDR_SPACE (TREE_TYPE (type));
        
      if (avr_log.progmem)
        avr_edump ("%?: type = %t\nexpr = %t\n\n", type, expr);

      if (as_new != ADDR_SPACE_MEMX
          && as_new != as_old)
        {
          location_t loc = EXPR_LOCATION (expr);
          const char *name_old = avr_addrspace[as_old].name;
          const char *name_new = avr_addrspace[as_new].name;

          warning (OPT_Waddr_space_convert,
                   "conversion from address space %qs to address space %qs",
                   ADDR_SPACE_GENERIC_P (as_old) ? "generic" : name_old,
                   ADDR_SPACE_GENERIC_P (as_new) ? "generic" : name_new);

          return fold_build1_loc (loc, ADDR_SPACE_CONVERT_EXPR, type, expr);
        }
    }

  return NULL_TREE;
}


/* Worker function for movmemhi expander.
   XOP[0]  Destination as MEM:BLK
   XOP[1]  Source      "     "
   XOP[2]  # Bytes to copy

   Return TRUE  if the expansion is accomplished.
   Return FALSE if the operand compination is not supported.  */

bool
avr_emit_movmemhi (rtx *xop)
{
  HOST_WIDE_INT count;
  enum machine_mode loop_mode;
  addr_space_t as = MEM_ADDR_SPACE (xop[1]);
  rtx loop_reg, addr1, a_src, a_dest, insn, xas;
  rtx a_hi8 = NULL_RTX;

  if (avr_mem_flash_p (xop[0]))
    return false;

  if (!CONST_INT_P (xop[2]))
    return false;

  count = INTVAL (xop[2]);
  if (count <= 0)
    return false;

  a_src  = XEXP (xop[1], 0);
  a_dest = XEXP (xop[0], 0);

  if (PSImode == GET_MODE (a_src))
    {
      gcc_assert (as == ADDR_SPACE_MEMX);

      loop_mode = (count < 0x100) ? QImode : HImode;
      loop_reg = gen_rtx_REG (loop_mode, 24);
      emit_move_insn (loop_reg, gen_int_mode (count, loop_mode));

      addr1 = simplify_gen_subreg (HImode, a_src, PSImode, 0);
      a_hi8 = simplify_gen_subreg (QImode, a_src, PSImode, 2);
    }
  else
    {
      int segment = avr_addrspace[as].segment;

      if (segment
          && avr_current_device->n_flash > 1)
        {
          a_hi8 = GEN_INT (segment);
          emit_move_insn (rampz_rtx, a_hi8 = copy_to_mode_reg (QImode, a_hi8));
        }
      else if (!ADDR_SPACE_GENERIC_P (as))
        {
          as = ADDR_SPACE_FLASH;
        }

      addr1 = a_src;

      loop_mode = (count <= 0x100) ? QImode : HImode;
      loop_reg = copy_to_mode_reg (loop_mode, gen_int_mode (count, loop_mode));
    }

  xas = GEN_INT (as);

  /* FIXME: Register allocator might come up with spill fails if it is left
        on its own.  Thus, we allocate the pointer registers by hand:
        Z = source address
        X = destination address  */

  emit_move_insn (lpm_addr_reg_rtx, addr1);
  emit_move_insn (gen_rtx_REG (HImode, REG_X), a_dest);

  /* FIXME: Register allocator does a bad job and might spill address
        register(s) inside the loop leading to additional move instruction
        to/from stack which could clobber tmp_reg.  Thus, do *not* emit
        load and store as separate insns.  Instead, we perform the copy
        by means of one monolithic insn.  */

  gcc_assert (TMP_REGNO == LPM_REGNO);

  if (as != ADDR_SPACE_MEMX)
    {
      /* Load instruction ([E]LPM or LD) is known at compile time:
         Do the copy-loop inline.  */

      rtx (*fun) (rtx, rtx, rtx)
        = QImode == loop_mode ? gen_movmem_qi : gen_movmem_hi;

      insn = fun (xas, loop_reg, loop_reg);
    }
  else
    {
      rtx (*fun) (rtx, rtx)
        = QImode == loop_mode ? gen_movmemx_qi : gen_movmemx_hi;

      emit_move_insn (gen_rtx_REG (QImode, 23), a_hi8);

      insn = fun (xas, GEN_INT (avr_addr.rampz));
    }

  set_mem_addr_space (SET_SRC (XVECEXP (insn, 0, 0)), as);
  emit_insn (insn);

  return true;
}


/* Print assembler for movmem_qi, movmem_hi insns...
       $0     : Address Space
       $1, $2 : Loop register
       Z      : Source address
       X      : Destination address
*/

const char*
avr_out_movmem (rtx insn ATTRIBUTE_UNUSED, rtx *op, int *plen)
{
  addr_space_t as = (addr_space_t) INTVAL (op[0]);
  enum machine_mode loop_mode = GET_MODE (op[1]);
  bool sbiw_p = test_hard_reg_class (ADDW_REGS, op[1]);
  rtx xop[3];

  if (plen)
    *plen = 0;

  xop[0] = op[0];
  xop[1] = op[1];
  xop[2] = tmp_reg_rtx;

  /* Loop label */

  avr_asm_len ("0:", xop, plen, 0);

  /* Load with post-increment */

  switch (as)
    {
    default:
      gcc_unreachable();

    case ADDR_SPACE_GENERIC:

      avr_asm_len ("ld %2,Z+", xop, plen, 1);
      break;

    case ADDR_SPACE_FLASH:

      if (AVR_HAVE_LPMX)
        avr_asm_len ("lpm %2,Z+", xop, plen, 1);
      else
        avr_asm_len ("lpm" CR_TAB
                     "adiw r30,1", xop, plen, 2);
      break;

    case ADDR_SPACE_FLASH1:
    case ADDR_SPACE_FLASH2:
    case ADDR_SPACE_FLASH3:
    case ADDR_SPACE_FLASH4:
    case ADDR_SPACE_FLASH5:

      if (AVR_HAVE_ELPMX)
        avr_asm_len ("elpm %2,Z+", xop, plen, 1);
      else
        avr_asm_len ("elpm" CR_TAB
                     "adiw r30,1", xop, plen, 2);
      break;
    }

  /* Store with post-increment */

  avr_asm_len ("st X+,%2", xop, plen, 1);

  /* Decrement loop-counter and set Z-flag */

  if (QImode == loop_mode)
    {
      avr_asm_len ("dec %1", xop, plen, 1);
    }
  else if (sbiw_p)
    {
      avr_asm_len ("sbiw %1,1", xop, plen, 1);
    }
  else
    {
      avr_asm_len ("subi %A1,1" CR_TAB
                   "sbci %B1,0", xop, plen, 2);
    }

  /* Loop until zero */

  return avr_asm_len ("brne 0b", xop, plen, 1);
}



/* Helper for __builtin_avr_delay_cycles */

static rtx
avr_mem_clobber (void)
{
  rtx mem = gen_rtx_MEM (BLKmode, gen_rtx_SCRATCH (Pmode));
  MEM_VOLATILE_P (mem) = 1;
  return mem;
}

static void
avr_expand_delay_cycles (rtx operands0)
{
  unsigned HOST_WIDE_INT cycles = UINTVAL (operands0) & GET_MODE_MASK (SImode);
  unsigned HOST_WIDE_INT cycles_used;
  unsigned HOST_WIDE_INT loop_count;

  if (IN_RANGE (cycles, 83886082, 0xFFFFFFFF))
    {
      loop_count = ((cycles - 9) / 6) + 1;
      cycles_used = ((loop_count - 1) * 6) + 9;
      emit_insn (gen_delay_cycles_4 (gen_int_mode (loop_count, SImode),
                                     avr_mem_clobber()));
      cycles -= cycles_used;
    }

  if (IN_RANGE (cycles, 262145, 83886081))
    {
      loop_count = ((cycles - 7) / 5) + 1;
      if (loop_count > 0xFFFFFF)
        loop_count = 0xFFFFFF;
      cycles_used = ((loop_count - 1) * 5) + 7;
      emit_insn (gen_delay_cycles_3 (gen_int_mode (loop_count, SImode),
                                     avr_mem_clobber()));
      cycles -= cycles_used;
    }

  if (IN_RANGE (cycles, 768, 262144))
    {
      loop_count = ((cycles - 5) / 4) + 1;
      if (loop_count > 0xFFFF)
        loop_count = 0xFFFF;
      cycles_used = ((loop_count - 1) * 4) + 5;
      emit_insn (gen_delay_cycles_2 (gen_int_mode (loop_count, HImode),
                                     avr_mem_clobber()));
      cycles -= cycles_used;
    }

  if (IN_RANGE (cycles, 6, 767))
    {
      loop_count = cycles / 3;
      if (loop_count > 255)
        loop_count = 255;
      cycles_used = loop_count * 3;
      emit_insn (gen_delay_cycles_1 (gen_int_mode (loop_count, QImode),
                                     avr_mem_clobber()));
      cycles -= cycles_used;
      }

  while (cycles >= 2)
    {
      emit_insn (gen_nopv (GEN_INT(2)));
      cycles -= 2;
    }

  if (cycles == 1)
    {
      emit_insn (gen_nopv (GEN_INT(1)));
      cycles--;
    }
}


/* Compute the image of x under f, i.e. perform   x --> f(x)    */

static int
avr_map (unsigned int f, int x)
{
  return x < 8 ? (f >> (4 * x)) & 0xf : 0;
}


/* Return some metrics of map A.  */

enum
  {
    /* Number of fixed points in { 0 ... 7 } */
    MAP_FIXED_0_7,

    /* Size of preimage of non-fixed points in { 0 ... 7 } */
    MAP_NONFIXED_0_7,

    /* Mask representing the fixed points in { 0 ... 7 } */
    MAP_MASK_FIXED_0_7,

    /* Size of the preimage of { 0 ... 7 } */
    MAP_PREIMAGE_0_7,

    /* Mask that represents the preimage of { f } */
    MAP_MASK_PREIMAGE_F
  };

static unsigned
avr_map_metric (unsigned int a, int mode)
{
  unsigned i, metric = 0;

  for (i = 0; i < 8; i++)
    {
      unsigned ai = avr_map (a, i);

      if (mode == MAP_FIXED_0_7)
        metric += ai == i;
      else if (mode == MAP_NONFIXED_0_7)
        metric += ai < 8 && ai != i;
      else if (mode == MAP_MASK_FIXED_0_7)
        metric |= ((unsigned) (ai == i)) << i;
      else if (mode == MAP_PREIMAGE_0_7)
        metric += ai < 8;
      else if (mode == MAP_MASK_PREIMAGE_F)
        metric |= ((unsigned) (ai == 0xf)) << i;
      else
        gcc_unreachable();
    }

  return metric;
}


/* Return true if IVAL has a 0xf in its hexadecimal representation
   and false, otherwise.  Only nibbles 0..7 are taken into account.
   Used as constraint helper for C0f and Cxf.  */

bool
avr_has_nibble_0xf (rtx ival)
{
  unsigned int map = UINTVAL (ival) & GET_MODE_MASK (SImode);
  return 0 != avr_map_metric (map, MAP_MASK_PREIMAGE_F);
}


/* We have a set of bits that are mapped by a function F.
   Try to decompose F by means of a second function G so that

      F = F o G^-1 o G

   and

      cost (F o G^-1) + cost (G)  <  cost (F)

   Example:  Suppose builtin insert_bits supplies us with the map
   F = 0x3210ffff.  Instead of doing 4 bit insertions to get the high
   nibble of the result, we can just as well rotate the bits before inserting
   them and use the map 0x7654ffff which is cheaper than the original map.
   For this example G = G^-1 = 0x32107654 and F o G^-1 = 0x7654ffff.  */

typedef struct
{
  /* tree code of binary function G */
  enum tree_code code;

  /* The constant second argument of G */
  int arg;

  /* G^-1, the inverse of G (*, arg) */
  unsigned ginv;

  /* The cost of appplying G (*, arg) */
  int cost;

  /* The composition F o G^-1 (*, arg) for some function F */
  unsigned int map;

  /* For debug purpose only */
  const char *str;
} avr_map_op_t;

static const avr_map_op_t avr_map_op[] =
  {
    { LROTATE_EXPR, 0, 0x76543210, 0, 0, "id" },
    { LROTATE_EXPR, 1, 0x07654321, 2, 0, "<<<" },
    { LROTATE_EXPR, 2, 0x10765432, 4, 0, "<<<" },
    { LROTATE_EXPR, 3, 0x21076543, 4, 0, "<<<" },
    { LROTATE_EXPR, 4, 0x32107654, 1, 0, "<<<" },
    { LROTATE_EXPR, 5, 0x43210765, 3, 0, "<<<" },
    { LROTATE_EXPR, 6, 0x54321076, 5, 0, "<<<" },
    { LROTATE_EXPR, 7, 0x65432107, 3, 0, "<<<" },
    { RSHIFT_EXPR, 1, 0x6543210c, 1, 0, ">>" },
    { RSHIFT_EXPR, 1, 0x7543210c, 1, 0, ">>" },
    { RSHIFT_EXPR, 2, 0x543210cc, 2, 0, ">>" },
    { RSHIFT_EXPR, 2, 0x643210cc, 2, 0, ">>" },
    { RSHIFT_EXPR, 2, 0x743210cc, 2, 0, ">>" },
    { LSHIFT_EXPR, 1, 0xc7654321, 1, 0, "<<" },
    { LSHIFT_EXPR, 2, 0xcc765432, 2, 0, "<<" }
  };


/* Try to decompose F as F = (F o G^-1) o G as described above.
   The result is a struct representing F o G^-1 and G.
   If result.cost < 0 then such a decomposition does not exist.  */

static avr_map_op_t
avr_map_decompose (unsigned int f, const avr_map_op_t *g, bool val_const_p)
{
  int i;
  bool val_used_p = 0 != avr_map_metric (f, MAP_MASK_PREIMAGE_F);
  avr_map_op_t f_ginv = *g;
  unsigned int ginv = g->ginv;

  f_ginv.cost = -1;

  /* Step 1:  Computing F o G^-1  */

  for (i = 7; i >= 0; i--)
    {
      int x = avr_map (f, i);

      if (x <= 7)
        {
          x = avr_map (ginv, x);

          /* The bit is no element of the image of G: no avail (cost = -1)  */

          if (x > 7)
            return f_ginv;
        }

      f_ginv.map = (f_ginv.map << 4) + x;
    }

  /* Step 2:  Compute the cost of the operations.
     The overall cost of doing an operation prior to the insertion is
      the cost of the insertion plus the cost of the operation.  */

  /* Step 2a:  Compute cost of F o G^-1  */

  if (0 == avr_map_metric (f_ginv.map, MAP_NONFIXED_0_7))
    {
      /* The mapping consists only of fixed points and can be folded
         to AND/OR logic in the remainder.  Reasonable cost is 3. */

      f_ginv.cost = 2 + (val_used_p && !val_const_p);
    }
  else
    {
      rtx xop[4];

      /* Get the cost of the insn by calling the output worker with some
         fake values.  Mimic effect of reloading xop[3]: Unused operands
         are mapped to 0 and used operands are reloaded to xop[0].  */

      xop[0] = all_regs_rtx[24];
      xop[1] = gen_int_mode (f_ginv.map, SImode);
      xop[2] = all_regs_rtx[25];
      xop[3] = val_used_p ? xop[0] : const0_rtx;

      avr_out_insert_bits (xop, &f_ginv.cost);

      f_ginv.cost += val_const_p && val_used_p ? 1 : 0;
    }

  /* Step 2b:  Add cost of G  */

  f_ginv.cost += g->cost;

  if (avr_log.builtin)
    avr_edump (" %s%d=%d", g->str, g->arg, f_ginv.cost);

  return f_ginv;
}


/* Insert bits from XOP[1] into XOP[0] according to MAP.
   XOP[0] and XOP[1] don't overlap.
   If FIXP_P = true:  Move all bits according to MAP using BLD/BST sequences.
   If FIXP_P = false: Just move the bit if its position in the destination
   is different to its source position.  */

static void
avr_move_bits (rtx *xop, unsigned int map, bool fixp_p, int *plen)
{
  int bit_dest, b;

  /* T-flag contains this bit of the source, i.e. of XOP[1]  */
  int t_bit_src = -1;

  /* We order the operations according to the requested source bit b.  */

  for (b = 0; b < 8; b++)
    for (bit_dest = 0; bit_dest < 8; bit_dest++)
      {
        int bit_src = avr_map (map, bit_dest);

        if (b != bit_src
            || bit_src >= 8
            /* Same position: No need to copy as requested by FIXP_P.  */
            || (bit_dest == bit_src && !fixp_p))
          continue;

        if (t_bit_src != bit_src)
          {
            /* Source bit is not yet in T: Store it to T.  */

            t_bit_src = bit_src;

            xop[3] = GEN_INT (bit_src);
            avr_asm_len ("bst %T1%T3", xop, plen, 1);
          }

        /* Load destination bit with T.  */

        xop[3] = GEN_INT (bit_dest);
        avr_asm_len ("bld %T0%T3", xop, plen, 1);
      }
}


/* PLEN == 0: Print assembler code for `insert_bits'.
   PLEN != 0: Compute code length in bytes.

   OP[0]:  Result
   OP[1]:  The mapping composed of nibbles. If nibble no. N is
           0:   Bit N of result is copied from bit OP[2].0
           ...  ...
           7:   Bit N of result is copied from bit OP[2].7
           0xf: Bit N of result is copied from bit OP[3].N
   OP[2]:  Bits to be inserted
   OP[3]:  Target value  */

const char*
avr_out_insert_bits (rtx *op, int *plen)
{
  unsigned int map = UINTVAL (op[1]) & GET_MODE_MASK (SImode);
  unsigned mask_fixed;
  bool fixp_p = true;
  rtx xop[4];

  xop[0] = op[0];
  xop[1] = op[2];
  xop[2] = op[3];

  gcc_assert (REG_P (xop[2]) || CONST_INT_P (xop[2]));

  if (plen)
    *plen = 0;
  else if (flag_print_asm_name)
    fprintf (asm_out_file, ASM_COMMENT_START "map = 0x%08x\n", map);

  /* If MAP has fixed points it might be better to initialize the result
     with the bits to be inserted instead of moving all bits by hand.  */

  mask_fixed = avr_map_metric (map, MAP_MASK_FIXED_0_7);

  if (REGNO (xop[0]) == REGNO (xop[1]))
    {
      /* Avoid early-clobber conflicts */

      avr_asm_len ("mov __tmp_reg__,%1", xop, plen, 1);
      xop[1] = tmp_reg_rtx;
      fixp_p = false;
    }

  if (avr_map_metric (map, MAP_MASK_PREIMAGE_F))
    {
      /* XOP[2] is used and reloaded to XOP[0] already */

      int n_fix = 0, n_nofix = 0;

      gcc_assert (REG_P (xop[2]));

      /* Get the code size of the bit insertions; once with all bits
         moved and once with fixed points omitted.  */

      avr_move_bits (xop, map, true, &n_fix);
      avr_move_bits (xop, map, false, &n_nofix);

      if (fixp_p && n_fix - n_nofix > 3)
        {
          xop[3] = gen_int_mode (~mask_fixed, QImode);

          avr_asm_len ("eor %0,%1"   CR_TAB
                       "andi %0,%3"  CR_TAB
                       "eor %0,%1", xop, plen, 3);
          fixp_p = false;
        }
    }
  else
    {
      /* XOP[2] is unused */

      if (fixp_p && mask_fixed)
        {
          avr_asm_len ("mov %0,%1", xop, plen, 1);
          fixp_p = false;
        }
    }

  /* Move/insert remaining bits.  */

  avr_move_bits (xop, map, fixp_p, plen);

  return "";
}


/* IDs for all the AVR builtins.  */

enum avr_builtin_id
  {
#define DEF_BUILTIN(NAME, N_ARGS, TYPE, CODE, LIBNAME)  \
    AVR_BUILTIN_ ## NAME,
#include "builtins.def"
#undef DEF_BUILTIN

    AVR_BUILTIN_COUNT
  };

struct GTY(()) avr_builtin_description
{
  enum insn_code icode;
  int n_args;
  tree fndecl;
};


/* Notice that avr_bdesc[] and avr_builtin_id are initialized in such a way
   that a built-in's ID can be used to access the built-in by means of
   avr_bdesc[ID]  */

static GTY(()) struct avr_builtin_description
avr_bdesc[AVR_BUILTIN_COUNT] =
  {
#define DEF_BUILTIN(NAME, N_ARGS, TYPE, ICODE, LIBNAME)         \
    { (enum insn_code) CODE_FOR_ ## ICODE, N_ARGS, NULL_TREE },
#include "builtins.def"
#undef DEF_BUILTIN
  };


/* Implement `TARGET_BUILTIN_DECL'.  */

static tree
avr_builtin_decl (unsigned id, bool initialize_p ATTRIBUTE_UNUSED)
{
  if (id < AVR_BUILTIN_COUNT)
    return avr_bdesc[id].fndecl;

  return error_mark_node;
}


static void
avr_init_builtin_int24 (void)
{
  tree int24_type  = make_signed_type (GET_MODE_BITSIZE (PSImode));
  tree uint24_type = make_unsigned_type (GET_MODE_BITSIZE (PSImode));

  lang_hooks.types.register_builtin_type (int24_type, "__int24");
  lang_hooks.types.register_builtin_type (uint24_type, "__uint24");
}


/* Implement `TARGET_INIT_BUILTINS' */
/* Set up all builtin functions for this target.  */

static void
avr_init_builtins (void)
{
  tree void_ftype_void
    = build_function_type_list (void_type_node, NULL_TREE);
  tree uchar_ftype_uchar
    = build_function_type_list (unsigned_char_type_node,
                                unsigned_char_type_node,
                                NULL_TREE);
  tree uint_ftype_uchar_uchar
    = build_function_type_list (unsigned_type_node,
                                unsigned_char_type_node,
                                unsigned_char_type_node,
                                NULL_TREE);
  tree int_ftype_char_char
    = build_function_type_list (integer_type_node,
                                char_type_node,
                                char_type_node,
                                NULL_TREE);
  tree int_ftype_char_uchar
    = build_function_type_list (integer_type_node,
                                char_type_node,
                                unsigned_char_type_node,
                                NULL_TREE);
  tree void_ftype_ulong
    = build_function_type_list (void_type_node,
                                long_unsigned_type_node,
                                NULL_TREE);

  tree uchar_ftype_ulong_uchar_uchar
    = build_function_type_list (unsigned_char_type_node,
                                long_unsigned_type_node,
                                unsigned_char_type_node,
                                unsigned_char_type_node,
                                NULL_TREE);

  tree const_memx_void_node
    = build_qualified_type (void_type_node,
                            TYPE_QUAL_CONST
                            | ENCODE_QUAL_ADDR_SPACE (ADDR_SPACE_MEMX));

  tree const_memx_ptr_type_node
    = build_pointer_type_for_mode (const_memx_void_node, PSImode, false);

  tree char_ftype_const_memx_ptr
    = build_function_type_list (char_type_node,
                                const_memx_ptr_type_node,
                                NULL);

#define ITYP(T)                                                         \
  lang_hooks.types.type_for_size (TYPE_PRECISION (T), TYPE_UNSIGNED (T))
  
#define FX_FTYPE_FX(fx)                                                 \
  tree fx##r_ftype_##fx##r                                              \
    = build_function_type_list (node_##fx##r, node_##fx##r, NULL);      \
  tree fx##k_ftype_##fx##k                                              \
    = build_function_type_list (node_##fx##k, node_##fx##k, NULL)

#define FX_FTYPE_FX_INT(fx)                                             \
  tree fx##r_ftype_##fx##r_int                                          \
    = build_function_type_list (node_##fx##r, node_##fx##r,             \
                                integer_type_node, NULL);               \
  tree fx##k_ftype_##fx##k_int                                          \
    = build_function_type_list (node_##fx##k, node_##fx##k,             \
                                integer_type_node, NULL)
  
#define INT_FTYPE_FX(fx)                                                \
  tree int_ftype_##fx##r                                                \
    = build_function_type_list (integer_type_node, node_##fx##r, NULL); \
  tree int_ftype_##fx##k                                                \
    = build_function_type_list (integer_type_node, node_##fx##k, NULL)

#define INTX_FTYPE_FX(fx)                                               \
  tree int##fx##r_ftype_##fx##r                                         \
    = build_function_type_list (ITYP (node_##fx##r), node_##fx##r, NULL); \
  tree int##fx##k_ftype_##fx##k                                         \
    = build_function_type_list (ITYP (node_##fx##k), node_##fx##k, NULL)

#define FX_FTYPE_INTX(fx)                                               \
  tree fx##r_ftype_int##fx##r                                           \
    = build_function_type_list (node_##fx##r, ITYP (node_##fx##r), NULL); \
  tree fx##k_ftype_int##fx##k                                           \
    = build_function_type_list (node_##fx##k, ITYP (node_##fx##k), NULL)

  tree node_hr = short_fract_type_node;
  tree node_nr = fract_type_node;
  tree node_lr = long_fract_type_node;
  tree node_llr = long_long_fract_type_node;

  tree node_uhr = unsigned_short_fract_type_node;
  tree node_unr = unsigned_fract_type_node;
  tree node_ulr = unsigned_long_fract_type_node;
  tree node_ullr = unsigned_long_long_fract_type_node;

  tree node_hk = short_accum_type_node;
  tree node_nk = accum_type_node;
  tree node_lk = long_accum_type_node;
  tree node_llk = long_long_accum_type_node;

  tree node_uhk = unsigned_short_accum_type_node;
  tree node_unk = unsigned_accum_type_node;
  tree node_ulk = unsigned_long_accum_type_node;
  tree node_ullk = unsigned_long_long_accum_type_node;


  /* For absfx builtins.  */

  FX_FTYPE_FX (h);
  FX_FTYPE_FX (n);
  FX_FTYPE_FX (l);
  FX_FTYPE_FX (ll);

  /* For roundfx builtins.  */

  FX_FTYPE_FX_INT (h);
  FX_FTYPE_FX_INT (n);
  FX_FTYPE_FX_INT (l);
  FX_FTYPE_FX_INT (ll);

  FX_FTYPE_FX_INT (uh);
  FX_FTYPE_FX_INT (un);
  FX_FTYPE_FX_INT (ul);
  FX_FTYPE_FX_INT (ull);

  /* For countlsfx builtins.  */

  INT_FTYPE_FX (h);
  INT_FTYPE_FX (n);
  INT_FTYPE_FX (l);
  INT_FTYPE_FX (ll);

  INT_FTYPE_FX (uh);
  INT_FTYPE_FX (un);
  INT_FTYPE_FX (ul);
  INT_FTYPE_FX (ull);

  /* For bitsfx builtins.  */

  INTX_FTYPE_FX (h);
  INTX_FTYPE_FX (n);
  INTX_FTYPE_FX (l);
  INTX_FTYPE_FX (ll);

  INTX_FTYPE_FX (uh);
  INTX_FTYPE_FX (un);
  INTX_FTYPE_FX (ul);
  INTX_FTYPE_FX (ull);

  /* For fxbits builtins.  */

  FX_FTYPE_INTX (h);
  FX_FTYPE_INTX (n);
  FX_FTYPE_INTX (l);
  FX_FTYPE_INTX (ll);

  FX_FTYPE_INTX (uh);
  FX_FTYPE_INTX (un);
  FX_FTYPE_INTX (ul);
  FX_FTYPE_INTX (ull);


#define DEF_BUILTIN(NAME, N_ARGS, TYPE, CODE, LIBNAME)                  \
  {                                                                     \
    int id = AVR_BUILTIN_ ## NAME;                                      \
    const char *Name = "__builtin_avr_" #NAME;                          \
    char *name = (char*) alloca (1 + strlen (Name));                    \
                                                                        \
    gcc_assert (id < AVR_BUILTIN_COUNT);                                \
    avr_bdesc[id].fndecl                                                \
      = add_builtin_function (avr_tolower (name, Name), TYPE, id,       \
                              BUILT_IN_MD, LIBNAME, NULL_TREE);         \
  }
#include "builtins.def"
#undef DEF_BUILTIN

  avr_init_builtin_int24 ();
}


/* Subroutine of avr_expand_builtin to expand vanilla builtins
   with non-void result and 1 ... 3 arguments.  */

static rtx
avr_default_expand_builtin (enum insn_code icode, tree exp, rtx target)
{
  rtx pat, xop[3];
  int n, n_args = call_expr_nargs (exp);
  enum machine_mode tmode = insn_data[icode].operand[0].mode;

  gcc_assert (n_args >= 1 && n_args <= 3);

  if (target == NULL_RTX
      || GET_MODE (target) != tmode
      || !insn_data[icode].operand[0].predicate (target, tmode))
    {
      target = gen_reg_rtx (tmode);
    }

  for (n = 0; n < n_args; n++)
    {
      tree arg = CALL_EXPR_ARG (exp, n);
      rtx op = expand_expr (arg, NULL_RTX, VOIDmode, EXPAND_NORMAL);
      enum machine_mode opmode = GET_MODE (op);
      enum machine_mode mode = insn_data[icode].operand[n+1].mode;

      if ((opmode == SImode || opmode == VOIDmode) && mode == HImode)
        {
          opmode = HImode;
          op = gen_lowpart (HImode, op);
        }

      /* In case the insn wants input operands in modes different from
         the result, abort.  */

      gcc_assert (opmode == mode || opmode == VOIDmode);

      if (!insn_data[icode].operand[n+1].predicate (op, mode))
        op = copy_to_mode_reg (mode, op);

      xop[n] = op;
    }

  switch (n_args)
    {
    case 1: pat = GEN_FCN (icode) (target, xop[0]); break;
    case 2: pat = GEN_FCN (icode) (target, xop[0], xop[1]); break;
    case 3: pat = GEN_FCN (icode) (target, xop[0], xop[1], xop[2]); break;

    default:
      gcc_unreachable();
    }

  if (pat == NULL_RTX)
    return NULL_RTX;

  emit_insn (pat);

  return target;
}


/* Implement `TARGET_EXPAND_BUILTIN'.  */
/* Expand an expression EXP that calls a built-in function,
   with result going to TARGET if that's convenient
   (and in mode MODE if that's convenient).
   SUBTARGET may be used as the target for computing one of EXP's operands.
   IGNORE is nonzero if the value is to be ignored.  */

static rtx
avr_expand_builtin (tree exp, rtx target,
                    rtx subtarget ATTRIBUTE_UNUSED,
                    enum machine_mode mode ATTRIBUTE_UNUSED,
                    int ignore)
{
  tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
  const char *bname = IDENTIFIER_POINTER (DECL_NAME (fndecl));
  unsigned int id = DECL_FUNCTION_CODE (fndecl);
  const struct avr_builtin_description *d = &avr_bdesc[id];
  tree arg0;
  rtx op0;

  gcc_assert (id < AVR_BUILTIN_COUNT);

  switch (id)
    {
    case AVR_BUILTIN_NOP:
      emit_insn (gen_nopv (GEN_INT(1)));
      return 0;

    case AVR_BUILTIN_DELAY_CYCLES:
      {
        arg0 = CALL_EXPR_ARG (exp, 0);
        op0 = expand_expr (arg0, NULL_RTX, VOIDmode, EXPAND_NORMAL);

        if (!CONST_INT_P (op0))
          error ("%s expects a compile time integer constant", bname);
        else
          avr_expand_delay_cycles (op0);

        return NULL_RTX;
      }

    case AVR_BUILTIN_INSERT_BITS:
      {
        arg0 = CALL_EXPR_ARG (exp, 0);
        op0 = expand_expr (arg0, NULL_RTX, VOIDmode, EXPAND_NORMAL);

        if (!CONST_INT_P (op0))
          {
            error ("%s expects a compile time long integer constant"
                   " as first argument", bname);
            return target;
          }

        break;
      }

    case AVR_BUILTIN_ROUNDHR:   case AVR_BUILTIN_ROUNDUHR:
    case AVR_BUILTIN_ROUNDR:    case AVR_BUILTIN_ROUNDUR:
    case AVR_BUILTIN_ROUNDLR:   case AVR_BUILTIN_ROUNDULR:
    case AVR_BUILTIN_ROUNDLLR:  case AVR_BUILTIN_ROUNDULLR:

    case AVR_BUILTIN_ROUNDHK:   case AVR_BUILTIN_ROUNDUHK:
    case AVR_BUILTIN_ROUNDK:    case AVR_BUILTIN_ROUNDUK:
    case AVR_BUILTIN_ROUNDLK:   case AVR_BUILTIN_ROUNDULK:
    case AVR_BUILTIN_ROUNDLLK:  case AVR_BUILTIN_ROUNDULLK:

      /* Warn about odd rounding.  Rounding points >= FBIT will have
         no effect.  */
      
      if (TREE_CODE (CALL_EXPR_ARG (exp, 1)) != INTEGER_CST)
        break;

      int rbit = (int) TREE_INT_CST_LOW (CALL_EXPR_ARG (exp, 1));

      if (rbit >= (int) GET_MODE_FBIT (mode))
        {
          warning (OPT_Wextra, "rounding to %d bits has no effect for "
                   "fixed-point value with %d fractional bits",
                   rbit, GET_MODE_FBIT (mode));

          return expand_expr (CALL_EXPR_ARG (exp, 0), NULL_RTX, mode,
                              EXPAND_NORMAL);
        }
      else if (rbit <= - (int) GET_MODE_IBIT (mode))
        {
          warning (0, "rounding result will always be 0");
          return CONST0_RTX (mode);
        }

      /* The rounding points RP satisfies now:  -IBIT < RP < FBIT.

         TR 18037 only specifies results for  RP > 0.  However, the
         remaining cases of  -IBIT < RP <= 0  can easily be supported
         without any additional overhead.  */

      break; /* round */
    }

  /* No fold found and no insn:  Call support function from libgcc.  */

  if (d->icode == CODE_FOR_nothing
      && DECL_ASSEMBLER_NAME (get_callee_fndecl (exp)) != NULL_TREE)
    {
      return expand_call (exp, target, ignore);
    }

  /* No special treatment needed: vanilla expand.  */

  gcc_assert (d->icode != CODE_FOR_nothing);
  gcc_assert (d->n_args == call_expr_nargs (exp));

  if (d->n_args == 0)
    {
      emit_insn ((GEN_FCN (d->icode)) (target));
      return NULL_RTX;
    }

  return avr_default_expand_builtin (d->icode, exp, target);
}


/* Helper for `avr_fold_builtin' that folds  absfx (FIXED_CST).  */

static tree
avr_fold_absfx (tree tval)
{
  if (FIXED_CST != TREE_CODE (tval))
    return NULL_TREE;

  /* Our fixed-points have no padding:  Use double_int payload directly.  */

  FIXED_VALUE_TYPE fval = TREE_FIXED_CST (tval);
  unsigned int bits = GET_MODE_BITSIZE (fval.mode);
  double_int ival = fval.data.sext (bits);

  if (!ival.is_negative())
    return tval;

  /* ISO/IEC TR 18037, 7.18a.6.2:  The absfx functions are saturating.  */

  fval.data = (ival == double_int::min_value (bits, false).sext (bits))
    ? double_int::max_value (bits, false)
    : -ival;

  return build_fixed (TREE_TYPE (tval), fval);
}


/* Implement `TARGET_FOLD_BUILTIN'.  */

static tree
avr_fold_builtin (tree fndecl, int n_args ATTRIBUTE_UNUSED, tree *arg,
                  bool ignore ATTRIBUTE_UNUSED)
{
  unsigned int fcode = DECL_FUNCTION_CODE (fndecl);
  tree val_type = TREE_TYPE (TREE_TYPE (fndecl));

  if (!optimize)
    return NULL_TREE;

  switch (fcode)
    {
    default:
      break;

    case AVR_BUILTIN_SWAP:
      {
        return fold_build2 (LROTATE_EXPR, val_type, arg[0],
                            build_int_cst (val_type, 4));
      }

    case AVR_BUILTIN_ABSHR:
    case AVR_BUILTIN_ABSR:
    case AVR_BUILTIN_ABSLR:
    case AVR_BUILTIN_ABSLLR:

    case AVR_BUILTIN_ABSHK:
    case AVR_BUILTIN_ABSK:
    case AVR_BUILTIN_ABSLK:
    case AVR_BUILTIN_ABSLLK:
      /* GCC is not good with folding ABS for fixed-point.  Do it by hand.  */

      return avr_fold_absfx (arg[0]);

    case AVR_BUILTIN_BITSHR:    case AVR_BUILTIN_HRBITS:
    case AVR_BUILTIN_BITSHK:    case AVR_BUILTIN_HKBITS:
    case AVR_BUILTIN_BITSUHR:   case AVR_BUILTIN_UHRBITS:
    case AVR_BUILTIN_BITSUHK:   case AVR_BUILTIN_UHKBITS:

    case AVR_BUILTIN_BITSR:     case AVR_BUILTIN_RBITS:
    case AVR_BUILTIN_BITSK:     case AVR_BUILTIN_KBITS:
    case AVR_BUILTIN_BITSUR:    case AVR_BUILTIN_URBITS:
    case AVR_BUILTIN_BITSUK:    case AVR_BUILTIN_UKBITS:

    case AVR_BUILTIN_BITSLR:    case AVR_BUILTIN_LRBITS:
    case AVR_BUILTIN_BITSLK:    case AVR_BUILTIN_LKBITS:
    case AVR_BUILTIN_BITSULR:   case AVR_BUILTIN_ULRBITS:
    case AVR_BUILTIN_BITSULK:   case AVR_BUILTIN_ULKBITS:

    case AVR_BUILTIN_BITSLLR:   case AVR_BUILTIN_LLRBITS:
    case AVR_BUILTIN_BITSLLK:   case AVR_BUILTIN_LLKBITS:
    case AVR_BUILTIN_BITSULLR:  case AVR_BUILTIN_ULLRBITS:
    case AVR_BUILTIN_BITSULLK:  case AVR_BUILTIN_ULLKBITS:

      gcc_assert (TYPE_PRECISION (val_type)
                  == TYPE_PRECISION (TREE_TYPE (arg[0])));

      return build1 (VIEW_CONVERT_EXPR, val_type, arg[0]);

    case AVR_BUILTIN_INSERT_BITS:
      {
        tree tbits = arg[1];
        tree tval = arg[2];
        tree tmap;
        tree map_type = TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (fndecl)));
        unsigned int map;
        bool changed = false;
        unsigned i;
        avr_map_op_t best_g;

        if (TREE_CODE (arg[0]) != INTEGER_CST)
          {
            /* No constant as first argument: Don't fold this and run into
               error in avr_expand_builtin.  */

            break;
          }

        tmap = double_int_to_tree (map_type, tree_to_double_int (arg[0]));
        map = TREE_INT_CST_LOW (tmap);

        if (TREE_CODE (tval) != INTEGER_CST
            && 0 == avr_map_metric (map, MAP_MASK_PREIMAGE_F))
          {
            /* There are no F in the map, i.e. 3rd operand is unused.
               Replace that argument with some constant to render
               respective input unused.  */

            tval = build_int_cst (val_type, 0);
            changed = true;
          }

        if (TREE_CODE (tbits) != INTEGER_CST
            && 0 == avr_map_metric (map, MAP_PREIMAGE_0_7))
          {
            /* Similar for the bits to be inserted. If they are unused,
               we can just as well pass 0.  */

            tbits = build_int_cst (val_type, 0);
          }

        if (TREE_CODE (tbits) == INTEGER_CST)
          {
            /* Inserting bits known at compile time is easy and can be
               performed by AND and OR with appropriate masks.  */

            int bits = TREE_INT_CST_LOW (tbits);
            int mask_ior = 0, mask_and = 0xff;

            for (i = 0; i < 8; i++)
              {
                int mi = avr_map (map, i);

                if (mi < 8)
                  {
                    if (bits & (1 << mi))     mask_ior |=  (1 << i);
                    else                      mask_and &= ~(1 << i);
                  }
              }

            tval = fold_build2 (BIT_IOR_EXPR, val_type, tval,
                                build_int_cst (val_type, mask_ior));
            return fold_build2 (BIT_AND_EXPR, val_type, tval,
                                build_int_cst (val_type, mask_and));
          }

        if (changed)
          return build_call_expr (fndecl, 3, tmap, tbits, tval);

        /* If bits don't change their position we can use vanilla logic
           to merge the two arguments.  */

        if (0 == avr_map_metric (map, MAP_NONFIXED_0_7))
          {
            int mask_f = avr_map_metric (map, MAP_MASK_PREIMAGE_F);
            tree tres, tmask = build_int_cst (val_type, mask_f ^ 0xff);

            tres = fold_build2 (BIT_XOR_EXPR, val_type, tbits, tval);
            tres = fold_build2 (BIT_AND_EXPR, val_type, tres, tmask);
            return fold_build2 (BIT_XOR_EXPR, val_type, tres, tval);
          }

        /* Try to decomposing map to reduce overall cost.  */

        if (avr_log.builtin)
          avr_edump ("\n%?: %x\n%?: ROL cost: ", map);

        best_g = avr_map_op[0];
        best_g.cost = 1000;

        for (i = 0; i < sizeof (avr_map_op) / sizeof (*avr_map_op); i++)
          {
            avr_map_op_t g
              = avr_map_decompose (map, avr_map_op + i,
                                   TREE_CODE (tval) == INTEGER_CST);

            if (g.cost >= 0 && g.cost < best_g.cost)
              best_g = g;
          }

        if (avr_log.builtin)
          avr_edump ("\n");

        if (best_g.arg == 0)
          /* No optimization found */
          break;

        /* Apply operation G to the 2nd argument.  */

        if (avr_log.builtin)
          avr_edump ("%?: using OP(%s%d, %x) cost %d\n",
                     best_g.str, best_g.arg, best_g.map, best_g.cost);

        /* Do right-shifts arithmetically: They copy the MSB instead of
           shifting in a non-usable value (0) as with logic right-shift.  */

        tbits = fold_convert (signed_char_type_node, tbits);
        tbits = fold_build2 (best_g.code, signed_char_type_node, tbits,
                             build_int_cst (val_type, best_g.arg));
        tbits = fold_convert (val_type, tbits);

        /* Use map o G^-1 instead of original map to undo the effect of G.  */

        tmap = double_int_to_tree (map_type,
				   double_int::from_uhwi (best_g.map));

        return build_call_expr (fndecl, 3, tmap, tbits, tval);
      } /* AVR_BUILTIN_INSERT_BITS */
    }

  return NULL_TREE;
}



/* Initialize the GCC target structure.  */

#undef  TARGET_ASM_ALIGNED_HI_OP
#define TARGET_ASM_ALIGNED_HI_OP "\t.word\t"
#undef  TARGET_ASM_ALIGNED_SI_OP
#define TARGET_ASM_ALIGNED_SI_OP "\t.long\t"
#undef  TARGET_ASM_UNALIGNED_HI_OP
#define TARGET_ASM_UNALIGNED_HI_OP "\t.word\t"
#undef  TARGET_ASM_UNALIGNED_SI_OP
#define TARGET_ASM_UNALIGNED_SI_OP "\t.long\t"
#undef  TARGET_ASM_INTEGER
#define TARGET_ASM_INTEGER avr_assemble_integer
#undef  TARGET_ASM_FILE_START
#define TARGET_ASM_FILE_START avr_file_start
#undef  TARGET_ASM_FILE_END
#define TARGET_ASM_FILE_END avr_file_end

#undef  TARGET_ASM_FUNCTION_END_PROLOGUE
#define TARGET_ASM_FUNCTION_END_PROLOGUE avr_asm_function_end_prologue
#undef  TARGET_ASM_FUNCTION_BEGIN_EPILOGUE
#define TARGET_ASM_FUNCTION_BEGIN_EPILOGUE avr_asm_function_begin_epilogue

#undef  TARGET_FUNCTION_VALUE
#define TARGET_FUNCTION_VALUE avr_function_value
#undef  TARGET_LIBCALL_VALUE
#define TARGET_LIBCALL_VALUE avr_libcall_value
#undef  TARGET_FUNCTION_VALUE_REGNO_P
#define TARGET_FUNCTION_VALUE_REGNO_P avr_function_value_regno_p

#undef  TARGET_ATTRIBUTE_TABLE
#define TARGET_ATTRIBUTE_TABLE avr_attribute_table
#undef  TARGET_INSERT_ATTRIBUTES
#define TARGET_INSERT_ATTRIBUTES avr_insert_attributes
#undef  TARGET_SECTION_TYPE_FLAGS
#define TARGET_SECTION_TYPE_FLAGS avr_section_type_flags

#undef  TARGET_ASM_NAMED_SECTION
#define TARGET_ASM_NAMED_SECTION avr_asm_named_section
#undef  TARGET_ASM_INIT_SECTIONS
#define TARGET_ASM_INIT_SECTIONS avr_asm_init_sections
#undef  TARGET_ENCODE_SECTION_INFO
#define TARGET_ENCODE_SECTION_INFO avr_encode_section_info
#undef  TARGET_ASM_SELECT_SECTION
#define TARGET_ASM_SELECT_SECTION avr_asm_select_section

#undef  TARGET_REGISTER_MOVE_COST
#define TARGET_REGISTER_MOVE_COST avr_register_move_cost
#undef  TARGET_MEMORY_MOVE_COST
#define TARGET_MEMORY_MOVE_COST avr_memory_move_cost
#undef  TARGET_RTX_COSTS
#define TARGET_RTX_COSTS avr_rtx_costs
#undef  TARGET_ADDRESS_COST
#define TARGET_ADDRESS_COST avr_address_cost
#undef  TARGET_MACHINE_DEPENDENT_REORG
#define TARGET_MACHINE_DEPENDENT_REORG avr_reorg
#undef  TARGET_FUNCTION_ARG
#define TARGET_FUNCTION_ARG avr_function_arg
#undef  TARGET_FUNCTION_ARG_ADVANCE
#define TARGET_FUNCTION_ARG_ADVANCE avr_function_arg_advance

#undef  TARGET_SET_CURRENT_FUNCTION
#define TARGET_SET_CURRENT_FUNCTION avr_set_current_function

#undef  TARGET_RETURN_IN_MEMORY
#define TARGET_RETURN_IN_MEMORY avr_return_in_memory

#undef  TARGET_STRICT_ARGUMENT_NAMING
#define TARGET_STRICT_ARGUMENT_NAMING hook_bool_CUMULATIVE_ARGS_true

#undef  TARGET_BUILTIN_SETJMP_FRAME_VALUE
#define TARGET_BUILTIN_SETJMP_FRAME_VALUE avr_builtin_setjmp_frame_value

#undef  TARGET_HARD_REGNO_SCRATCH_OK
#define TARGET_HARD_REGNO_SCRATCH_OK avr_hard_regno_scratch_ok
#undef  TARGET_CASE_VALUES_THRESHOLD
#define TARGET_CASE_VALUES_THRESHOLD avr_case_values_threshold

#undef  TARGET_FRAME_POINTER_REQUIRED
#define TARGET_FRAME_POINTER_REQUIRED avr_frame_pointer_required_p
#undef  TARGET_CAN_ELIMINATE
#define TARGET_CAN_ELIMINATE avr_can_eliminate

#undef  TARGET_ALLOCATE_STACK_SLOTS_FOR_ARGS
#define TARGET_ALLOCATE_STACK_SLOTS_FOR_ARGS avr_allocate_stack_slots_for_args

#undef TARGET_WARN_FUNC_RETURN
#define TARGET_WARN_FUNC_RETURN avr_warn_func_return

#undef  TARGET_CLASS_LIKELY_SPILLED_P
#define TARGET_CLASS_LIKELY_SPILLED_P avr_class_likely_spilled_p

#undef  TARGET_OPTION_OVERRIDE
#define TARGET_OPTION_OVERRIDE avr_option_override

#undef  TARGET_CANNOT_MODIFY_JUMPS_P
#define TARGET_CANNOT_MODIFY_JUMPS_P avr_cannot_modify_jumps_p

#undef  TARGET_FUNCTION_OK_FOR_SIBCALL
#define TARGET_FUNCTION_OK_FOR_SIBCALL avr_function_ok_for_sibcall

#undef  TARGET_INIT_BUILTINS
#define TARGET_INIT_BUILTINS avr_init_builtins

#undef  TARGET_BUILTIN_DECL
#define TARGET_BUILTIN_DECL avr_builtin_decl

#undef  TARGET_EXPAND_BUILTIN
#define TARGET_EXPAND_BUILTIN avr_expand_builtin

#undef  TARGET_FOLD_BUILTIN
#define TARGET_FOLD_BUILTIN avr_fold_builtin

#undef  TARGET_ASM_FUNCTION_RODATA_SECTION
#define TARGET_ASM_FUNCTION_RODATA_SECTION avr_asm_function_rodata_section

#undef  TARGET_SCALAR_MODE_SUPPORTED_P
#define TARGET_SCALAR_MODE_SUPPORTED_P avr_scalar_mode_supported_p

#undef  TARGET_BUILD_BUILTIN_VA_LIST
#define TARGET_BUILD_BUILTIN_VA_LIST avr_build_builtin_va_list

#undef  TARGET_FIXED_POINT_SUPPORTED_P
#define TARGET_FIXED_POINT_SUPPORTED_P hook_bool_void_true

#undef  TARGET_CONVERT_TO_TYPE
#define TARGET_CONVERT_TO_TYPE avr_convert_to_type

#undef  TARGET_ADDR_SPACE_SUBSET_P
#define TARGET_ADDR_SPACE_SUBSET_P avr_addr_space_subset_p

#undef  TARGET_ADDR_SPACE_CONVERT
#define TARGET_ADDR_SPACE_CONVERT avr_addr_space_convert

#undef  TARGET_ADDR_SPACE_ADDRESS_MODE
#define TARGET_ADDR_SPACE_ADDRESS_MODE avr_addr_space_address_mode

#undef  TARGET_ADDR_SPACE_POINTER_MODE
#define TARGET_ADDR_SPACE_POINTER_MODE avr_addr_space_pointer_mode

#undef  TARGET_ADDR_SPACE_LEGITIMATE_ADDRESS_P
#define TARGET_ADDR_SPACE_LEGITIMATE_ADDRESS_P  \
  avr_addr_space_legitimate_address_p

#undef  TARGET_ADDR_SPACE_LEGITIMIZE_ADDRESS
#define TARGET_ADDR_SPACE_LEGITIMIZE_ADDRESS avr_addr_space_legitimize_address

#undef  TARGET_MODE_DEPENDENT_ADDRESS_P
#define TARGET_MODE_DEPENDENT_ADDRESS_P avr_mode_dependent_address_p

#undef  TARGET_SECONDARY_RELOAD
#define TARGET_SECONDARY_RELOAD avr_secondary_reload

#undef  TARGET_PRINT_OPERAND
#define TARGET_PRINT_OPERAND avr_print_operand
#undef  TARGET_PRINT_OPERAND_ADDRESS
#define TARGET_PRINT_OPERAND_ADDRESS avr_print_operand_address
#undef  TARGET_PRINT_OPERAND_PUNCT_VALID_P
#define TARGET_PRINT_OPERAND_PUNCT_VALID_P avr_print_operand_punct_valid_p

struct gcc_target targetm = TARGET_INITIALIZER;


#include "gt-avr.h"