aboutsummaryrefslogtreecommitdiff
path: root/gcc/config/bpf/bpf.cc
blob: ea8ca64d1d6ee2291dd78b93abf338270903de71 (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
/* Subroutines used for code generation for eBPF.
   Copyright (C) 2019-2022 Free Software Foundation, Inc.

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/>.  */

#define IN_TARGET_CODE 1

#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "rtl.h"
#include "regs.h"
#include "insn-config.h"
#include "insn-attr.h"
#include "recog.h"
#include "output.h"
#include "alias.h"
#include "tree.h"
#include "stringpool.h"
#include "attribs.h"
#include "varasm.h"
#include "stor-layout.h"
#include "calls.h"
#include "function.h"
#include "explow.h"
#include "memmodel.h"
#include "emit-rtl.h"
#include "reload.h"
#include "tm_p.h"
#include "target.h"
#include "target-def.h"
#include "basic-block.h"
#include "expr.h"
#include "optabs.h"
#include "bitmap.h"
#include "df.h"
#include "c-family/c-common.h"
#include "diagnostic.h"
#include "builtins.h"
#include "predict.h"
#include "langhooks.h"
#include "flags.h"

#include "cfg.h" /* needed for struct control_flow_graph used in BB macros */
#include "gimple.h"
#include "gimple-iterator.h"
#include "gimple-walk.h"
#include "tree-pass.h"
#include "tree-iterator.h"

#include "context.h"
#include "pass_manager.h"

#include "gimplify.h"
#include "gimplify-me.h"

#include "ctfc.h"
#include "btf.h"

#include "coreout.h"

/* Per-function machine data.  */
struct GTY(()) machine_function
{
  /* Number of bytes saved on the stack for local variables.  */
  int local_vars_size;

  /* Number of bytes saved on the stack for callee-saved
     registers.  */
  int callee_saved_reg_size;
};

/* Handle an attribute requiring a FUNCTION_DECL;
   arguments as in struct attribute_spec.handler.  */

static tree
bpf_handle_fndecl_attribute (tree *node, tree name,
			     tree args,
			     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;
    }

  if (is_attribute_p ("kernel_helper", name))
    {
      if (args)
	{
	  tree cst = TREE_VALUE (args);
	  if (TREE_CODE (cst) != INTEGER_CST)
	    {
	      warning (OPT_Wattributes, "%qE attribute requires an integer argument",
		       name);
	      *no_add_attrs = true;
	    }
	}
      else
	{
	  warning (OPT_Wattributes, "%qE requires an argument", name);
	  *no_add_attrs = true;
	}
    }

  return NULL_TREE;
}

/* Handle preserve_access_index attribute, which can be applied to structs,
   unions and classes. Actually adding the attribute to the TYPE_DECL is
   taken care of for us, so just warn for types that aren't supported.  */

static tree
bpf_handle_preserve_access_index_attribute (tree *node, tree name,
					    tree args ATTRIBUTE_UNUSED,
					    int flags ATTRIBUTE_UNUSED,
					    bool *no_add_attrs)
{
  if (TREE_CODE (*node) != RECORD_TYPE && TREE_CODE (*node) != UNION_TYPE)
    {
      warning (OPT_Wattributes,
	       "%qE attribute only applies to structure, union and class types",
	       name);
      *no_add_attrs = true;
    }

  return NULL_TREE;
}

/* Target-specific attributes.  */

static const struct attribute_spec bpf_attribute_table[] =
{
  /* Syntax: { name, min_len, max_len, decl_required, type_required,
	       function_type_required, affects_type_identity, handler,
	       exclude } */

 /* Attribute to mark function prototypes as kernel helpers.  */
 { "kernel_helper", 1, 1, true, false, false, false,
   bpf_handle_fndecl_attribute, NULL },

 /* CO-RE support: attribute to mark that all accesses to the declared
    struct/union/array should be recorded.  */
 { "preserve_access_index", 0, -1, false, true, false, true,
   bpf_handle_preserve_access_index_attribute, NULL },

 /* The last attribute spec is set to be NULL.  */
 { NULL,	0,  0, false, false, false, false, NULL, NULL }
};

#undef TARGET_ATTRIBUTE_TABLE
#define TARGET_ATTRIBUTE_TABLE bpf_attribute_table

/* Data structures for the eBPF specific built-ins.  */

/* Maximum number of arguments taken by a builtin function, plus
   one.  */
#define BPF_BUILTIN_MAX_ARGS 5

enum bpf_builtins
{
  BPF_BUILTIN_UNUSED = 0,
  /* Built-ins for non-generic loads and stores.  */
  BPF_BUILTIN_LOAD_BYTE,
  BPF_BUILTIN_LOAD_HALF,
  BPF_BUILTIN_LOAD_WORD,

  /* Compile Once - Run Everywhere (CO-RE) support.  */
  BPF_BUILTIN_PRESERVE_ACCESS_INDEX,
  BPF_BUILTIN_PRESERVE_FIELD_INFO,

  BPF_BUILTIN_MAX,
};

static GTY (()) tree bpf_builtins[(int) BPF_BUILTIN_MAX];

void bpf_register_coreattr_pass (void);

/* Initialize the per-function machine status.  */

static struct machine_function *
bpf_init_machine_status (void)
{
  /* Note this initializes all fields to 0, which is just OK for
     us.  */
  return ggc_cleared_alloc<machine_function> ();
}

/* Override options and do some other initialization.  */

static void
bpf_option_override (void)
{
  /* Set the initializer for the per-function status structure.  */
  init_machine_status = bpf_init_machine_status;

  /* BPF CO-RE support requires BTF debug info generation.  */
  if (TARGET_BPF_CORE && !btf_debuginfo_p ())
    error ("BPF CO-RE requires BTF debugging information, use %<-gbtf%>");

  /* To support the portability needs of BPF CO-RE approach, BTF debug
     information includes the BPF CO-RE relocations.  */
  if (TARGET_BPF_CORE)
    write_symbols |= BTF_WITH_CORE_DEBUG;

  /* Unlike much of the other BTF debug information, the information necessary
     for CO-RE relocations is added to the CTF container by the BPF backend.
     Enabling LTO adds some complications in the generation of the BPF CO-RE
     relocations because if LTO is in effect, the relocations need to be
     generated late in the LTO link phase.  This poses a new challenge for the
     compiler to now provide means to combine the early BTF and late BTF CO-RE
     debug info, similar to DWARF debug info.  BTF/CO-RE debug info is not
     amenable to such a split generation and a later merging.

     In any case, in absence of linker support for BTF sections at this time,
     it is acceptable to simply disallow LTO for BPF CO-RE compilations.  */

  if (flag_lto && TARGET_BPF_CORE)
    sorry ("BPF CO-RE does not support LTO");

  /* -gbtf implies -mcore when using the BPF backend, unless -mno-co-re
     is specified.  */
  if (btf_debuginfo_p () && !(target_flags_explicit & MASK_BPF_CORE))
    {
      target_flags |= MASK_BPF_CORE;
      write_symbols |= BTF_WITH_CORE_DEBUG;
    }

  /* Determine available features from ISA setting (-mcpu=).  */
  if (bpf_has_jmpext == -1)
    bpf_has_jmpext = (bpf_isa >= ISA_V2);

  if (bpf_has_alu32 == -1)
    bpf_has_alu32 = (bpf_isa >= ISA_V3);

  if (bpf_has_jmp32 == -1)
    bpf_has_jmp32 = (bpf_isa >= ISA_V3);

}

#undef TARGET_OPTION_OVERRIDE
#define TARGET_OPTION_OVERRIDE bpf_option_override

/* Implement TARGET_ASM_INIT_SECTIONS.  */

static void
bpf_asm_init_sections (void)
{
  if (TARGET_BPF_CORE)
    btf_ext_init ();
}

#undef TARGET_ASM_INIT_SECTIONS
#define TARGET_ASM_INIT_SECTIONS bpf_asm_init_sections

/* Implement TARGET_ASM_FILE_END.  */

static void
bpf_file_end (void)
{
  if (TARGET_BPF_CORE)
    btf_ext_output ();
}

#undef TARGET_ASM_FILE_END
#define TARGET_ASM_FILE_END bpf_file_end

/* Define target-specific CPP macros.  This function in used in the
   definition of TARGET_CPU_CPP_BUILTINS in bpf.h */

#define builtin_define(TXT) cpp_define (pfile, TXT)

void
bpf_target_macros (cpp_reader *pfile)
{
  builtin_define ("__BPF__");
  builtin_define ("__bpf__");

  if (TARGET_BIG_ENDIAN)
    builtin_define ("__BPF_BIG_ENDIAN__");
  else
    builtin_define ("__BPF_LITTLE_ENDIAN__");

  /* Define BPF_KERNEL_VERSION_CODE */
  {
    const char *version_code;
    char *kernel_version_code;

    switch (bpf_kernel)
      {
      case LINUX_V4_0: version_code = "0x40000"; break;
      case LINUX_V4_1: version_code = "0x40100"; break;
      case LINUX_V4_2: version_code = "0x40200"; break;
      case LINUX_V4_3: version_code = "0x40300"; break;
      case LINUX_V4_4: version_code = "0x40400"; break;
      case LINUX_V4_5: version_code = "0x40500"; break;
      case LINUX_V4_6: version_code = "0x40600"; break;
      case LINUX_V4_7: version_code = "0x40700"; break;
      case LINUX_V4_8: version_code = "0x40800"; break;
      case LINUX_V4_9: version_code = "0x40900"; break;
      case LINUX_V4_10: version_code = "0x40a00"; break;
      case LINUX_V4_11: version_code = "0x40b00"; break;
      case LINUX_V4_12: version_code = "0x40c00"; break;
      case LINUX_V4_13: version_code = "0x40d00"; break;
      case LINUX_V4_14: version_code = "0x40e00"; break;
      case LINUX_V4_15: version_code = "0x40f00"; break;
      case LINUX_V4_16: version_code = "0x41000"; break;
      case LINUX_V4_17: version_code = "0x42000"; break;
      case LINUX_V4_18: version_code = "0x43000"; break;
      case LINUX_V4_19: version_code = "0x44000"; break;
      case LINUX_V4_20: version_code = "0x45000"; break;
      case LINUX_V5_0: version_code = "0x50000"; break;
      case LINUX_V5_1: version_code = "0x50100"; break;
      case LINUX_V5_2: version_code = "0x50200"; break;
      default:
	gcc_unreachable ();
      }

    kernel_version_code = ACONCAT (("__BPF_KERNEL_VERSION_CODE__=",
				    version_code, NULL));
    builtin_define (kernel_version_code);
  }
}

/* Return an RTX representing the place where a function returns or
   receives a value of data type RET_TYPE, a tree node representing a
   data type.  */

static rtx
bpf_function_value (const_tree ret_type,
		    const_tree fntype_or_decl,
		    bool outgoing ATTRIBUTE_UNUSED)
{
  enum machine_mode mode;
  int unsignedp;

  mode = TYPE_MODE (ret_type);
  if (INTEGRAL_TYPE_P (ret_type))
    mode = promote_function_mode (ret_type, mode, &unsignedp,
				  fntype_or_decl, 1);

  return gen_rtx_REG (mode, BPF_R0);
}

#undef TARGET_FUNCTION_VALUE
#define TARGET_FUNCTION_VALUE bpf_function_value

/* Return true if REGNO is the number of a hard register in which the
   values of called function may come back.  */

static bool
bpf_function_value_regno_p (const unsigned int regno)
{
  return (regno == BPF_R0);
}

#undef TARGET_FUNCTION_VALUE_REGNO_P
#define TARGET_FUNCTION_VALUE_REGNO_P bpf_function_value_regno_p

/* Compute the size of the function's stack frame, including the local
   area and the register-save area.  */

static void
bpf_compute_frame_layout (void)
{
  int stack_alignment = STACK_BOUNDARY / BITS_PER_UNIT;
  int padding_locals, regno;

  /* Set the space used in the stack by local variables.  This is
     rounded up to respect the minimum stack alignment.  */
  cfun->machine->local_vars_size = get_frame_size ();

  padding_locals = cfun->machine->local_vars_size % stack_alignment;
  if (padding_locals)
    padding_locals = stack_alignment - padding_locals;

  cfun->machine->local_vars_size += padding_locals;

  if (TARGET_XBPF)
    {
      /* Set the space used in the stack by callee-saved used
	 registers in the current function.  There is no need to round
	 up, since the registers are all 8 bytes wide.  */
      for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
	if ((df_regs_ever_live_p (regno)
	     && !call_used_or_fixed_reg_p (regno))
	    || (cfun->calls_alloca
		&& regno == STACK_POINTER_REGNUM))
	  cfun->machine->callee_saved_reg_size += 8;
    }

  /* Check that the total size of the frame doesn't exceed the limit
     imposed by eBPF.  */
  if ((cfun->machine->local_vars_size
       + cfun->machine->callee_saved_reg_size) > bpf_frame_limit)
    {
      static int stack_limit_exceeded = 0;

      if (!stack_limit_exceeded)
	error ("eBPF stack limit exceeded");
      stack_limit_exceeded = 1;
    }
}

#undef TARGET_COMPUTE_FRAME_LAYOUT
#define TARGET_COMPUTE_FRAME_LAYOUT bpf_compute_frame_layout

/* Expand to the instructions in a function prologue.  This function
   is called when expanding the 'prologue' pattern in bpf.md.  */

void
bpf_expand_prologue (void)
{
  HOST_WIDE_INT size;

  size = (cfun->machine->local_vars_size
	  + cfun->machine->callee_saved_reg_size);

  /* The BPF "hardware" provides a fresh new set of registers for each
     called function, some of which are initialized to the values of
     the arguments passed in the first five registers.  In doing so,
     it saves the values of the registers of the caller, and restored
     them upon returning.  Therefore, there is no need to save the
     callee-saved registers here.  What is worse, the kernel
     implementation refuses to run programs in which registers are
     referred before being initialized.  */
  if (TARGET_XBPF)
    {
      int regno;
      int fp_offset = -cfun->machine->local_vars_size;

      /* Save callee-saved hard registes.  The register-save-area
	 starts right after the local variables.  */
      for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
	{
	  if ((df_regs_ever_live_p (regno)
	       && !call_used_or_fixed_reg_p (regno))
	      || (cfun->calls_alloca
		  && regno == STACK_POINTER_REGNUM))
	    {
	      rtx mem;

	      if (!IN_RANGE (fp_offset, -1 - 0x7fff, 0x7fff))
		/* This has been already reported as an error in
		   bpf_compute_frame_layout. */
		break;
	      else
		{
		  mem = gen_frame_mem (DImode,
				       plus_constant (DImode,
						      hard_frame_pointer_rtx,
						      fp_offset - 8));
		  emit_move_insn (mem, gen_rtx_REG (DImode, regno));
		  fp_offset -= 8;
		}
	    }
	}
    }

  /* Set the stack pointer, if the function allocates space
     dynamically.  Note that the value of %sp should be directly
     derived from %fp, for the kernel verifier to track it as a stack
     accessor.  */
  if (cfun->calls_alloca)
    {
      emit_move_insn (stack_pointer_rtx,
                      hard_frame_pointer_rtx);

      if (size > 0)
	{
	  emit_insn (gen_rtx_SET (stack_pointer_rtx,
                                  gen_rtx_PLUS (Pmode,
                                                stack_pointer_rtx,
                                                GEN_INT (-size))));
	}
    }
}

/* Expand to the instructions in a function epilogue.  This function
   is called when expanding the 'epilogue' pattern in bpf.md.  */

void
bpf_expand_epilogue (void)
{
  /* See note in bpf_expand_prologue for an explanation on why we are
     not restoring callee-saved registers in BPF.  */
  if (TARGET_XBPF)
    {
      int regno;
      int fp_offset = -cfun->machine->local_vars_size;

      /* Restore callee-saved hard registes from the stack.  */
      for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
	{
	  if ((df_regs_ever_live_p (regno)
	       && !call_used_or_fixed_reg_p (regno))
	      || (cfun->calls_alloca
		  && regno == STACK_POINTER_REGNUM))
	    {
	      rtx mem;

	      if (!IN_RANGE (fp_offset, -1 - 0x7fff, 0x7fff))
		/* This has been already reported as an error in
		   bpf_compute_frame_layout. */
		break;
	      else
		{
		  mem = gen_frame_mem (DImode,
				       plus_constant (DImode,
						      hard_frame_pointer_rtx,
						      fp_offset - 8));
		  emit_move_insn (gen_rtx_REG (DImode, regno), mem);
		  fp_offset -= 8;
		}
	    }
	}
    }

  emit_jump_insn (gen_exit ());
}

/* Expand to the instructions for a conditional branch. This function
   is called when expanding the 'cbranch<mode>4' pattern in bpf.md.  */

void
bpf_expand_cbranch (machine_mode mode, rtx *operands)
{
  /* If all jump instructions are available, nothing special to do here.  */
  if (bpf_has_jmpext)
    return;

  enum rtx_code code = GET_CODE (operands[0]);

  /* Without the conditional branch instructions jslt, jsle, jlt, jle, we need
     to convert conditional branches that would use them to an available
     operation instead by reversing the comparison.  */
  if ((code == LT || code == LE || code == LTU || code == LEU))
    {
      /* Reverse the condition.  */
      PUT_CODE (operands[0], reverse_condition (code));

      /* Swap the operands, and ensure that the first is a register.  */
      if (!register_operand (operands[2], mode))
	operands[2] = force_reg (mode, operands[2]);

      rtx tmp = operands[1];
      operands[1] = operands[2];
      operands[2] = tmp;
    }
}

/* Return the initial difference between the specified pair of
   registers.  The registers that can figure in FROM, and TO, are
   specified by ELIMINABLE_REGS in bpf.h.

   This function is used in the definition of
   INITIAL_ELIMINATION_OFFSET in bpf.h  */

HOST_WIDE_INT
bpf_initial_elimination_offset (int from, int to)
{
  HOST_WIDE_INT ret;

  if (from == ARG_POINTER_REGNUM && to == STACK_POINTER_REGNUM)
    ret = (cfun->machine->local_vars_size
	   + cfun->machine->callee_saved_reg_size);
  else if (from == ARG_POINTER_REGNUM && to == FRAME_POINTER_REGNUM)
    ret = 0;
  else
    gcc_unreachable ();

  return ret;
}

/* Return the number of consecutive hard registers, starting at
   register number REGNO, required to hold a value of mode MODE.  */

static unsigned int
bpf_hard_regno_nregs (unsigned int regno ATTRIBUTE_UNUSED,
		      enum machine_mode mode)
{
  return CEIL (GET_MODE_SIZE (mode), UNITS_PER_WORD);
}

#undef TARGET_HARD_REGNO_NREGS
#define TARGET_HARD_REGNO_NREGS bpf_hard_regno_nregs

/* Return true if it is permissible to store a value of mode MODE in
   hard register number REGNO, or in several registers starting with
   that one.  */

static bool
bpf_hard_regno_mode_ok (unsigned int regno ATTRIBUTE_UNUSED,
			enum machine_mode mode)
{
  switch (mode)
    {
    case E_SImode:
    case E_DImode:
    case E_HImode:
    case E_QImode:
    case E_TImode:
    case E_SFmode:
    case E_DFmode:
      return true;
    default:
      return false;
    }
}

#undef TARGET_HARD_REGNO_MODE_OK
#define TARGET_HARD_REGNO_MODE_OK bpf_hard_regno_mode_ok

/* Return true if a function must have and use a frame pointer.  */

static bool
bpf_frame_pointer_required (void)
{
  /* We do not have a stack pointer, so we absolutely depend on the
     frame-pointer in order to access the stack... and fishes walk and
     pigs fly glglgl */
  return true;
}

#undef TARGET_FRAME_POINTER_REQUIRED
#define TARGET_FRAME_POINTER_REQUIRED bpf_frame_pointer_required

/* Return `true' if the given RTX X is a valid base for an indirect
   memory access.  STRICT has the same meaning than in
   bpf_legitimate_address_p.  */

static inline bool
bpf_address_base_p (rtx x, bool strict)
{
  return (GET_CODE (x) == REG
	  && (REGNO (x) < 11
	      || (!strict && REGNO (x) >= FIRST_PSEUDO_REGISTER)));
}

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

static bool
bpf_legitimate_address_p (machine_mode mode,
			  rtx x,
			  bool strict)
{
  switch (GET_CODE (x))
    {
    case CONST_INT:
      return (mode == FUNCTION_MODE);

    case REG:
      return bpf_address_base_p (x, strict);

    case PLUS:
      {
	/* Accept (PLUS ADDR_BASE CONST_INT), provided CONST_INT fits
	   in a signed 16-bit.

	   Note that LABEL_REF and SYMBOL_REF are not allowed in
	   REG+IMM addresses, because it is almost certain they will
	   overload the offset field.  */

	rtx x0 = XEXP (x, 0);
	rtx x1 = XEXP (x, 1);

	if (bpf_address_base_p (x0, strict) && GET_CODE (x1) == CONST_INT)
	  return IN_RANGE (INTVAL (x1), -1 - 0x7fff, 0x7fff);

	break;
      }
    default:
      break;
    }

  return false;
}

#undef TARGET_LEGITIMATE_ADDRESS_P
#define TARGET_LEGITIMATE_ADDRESS_P bpf_legitimate_address_p

/* Describe the relative costs of RTL expressions.  Return true when
   all subexpressions of X have been processed, and false when
   `rtx_cost' should recurse.  */

static bool
bpf_rtx_costs (rtx x ATTRIBUTE_UNUSED,
	       enum machine_mode mode ATTRIBUTE_UNUSED,
	       int outer_code ATTRIBUTE_UNUSED,
	       int opno ATTRIBUTE_UNUSED,
               int *total ATTRIBUTE_UNUSED,
	       bool speed ATTRIBUTE_UNUSED)
{
  /* To be written.  */
  return false;
}

#undef TARGET_RTX_COSTS
#define TARGET_RTX_COSTS bpf_rtx_costs

/* Return true if an argument at the position indicated by CUM should
   be passed by reference.  If the hook returns true, a copy of that
   argument is made in memory and a pointer to the argument is passed
   instead of the argument itself.  */

static bool
bpf_pass_by_reference (cumulative_args_t cum ATTRIBUTE_UNUSED,
		       const function_arg_info &arg)
{
  unsigned num_bytes = arg.type_size_in_bytes ();

  /* Pass aggregates and values bigger than 5 words by reference.
     Everything else is passed by copy.  */
  return (arg.aggregate_type_p () || (num_bytes > 8*5));
}

#undef TARGET_PASS_BY_REFERENCE
#define TARGET_PASS_BY_REFERENCE bpf_pass_by_reference

/* Return a RTX indicating whether a function argument is passed in a
   register and if so, which register.  */

static rtx
bpf_function_arg (cumulative_args_t ca, const function_arg_info &arg)
{
  CUMULATIVE_ARGS *cum = get_cumulative_args (ca);

  if (*cum < 5)
    return gen_rtx_REG (arg.mode, *cum + 1);
  else
    /* An error will be emitted for this in
       bpf_function_arg_advance.  */
    return NULL_RTX;
}

#undef TARGET_FUNCTION_ARG
#define TARGET_FUNCTION_ARG bpf_function_arg

/* Update the summarizer variable pointed by CA to advance past an
   argument in the argument list.  */

static void
bpf_function_arg_advance (cumulative_args_t ca,
			  const function_arg_info &arg)
{
  CUMULATIVE_ARGS *cum = get_cumulative_args (ca);
  unsigned num_bytes = arg.type_size_in_bytes ();
  unsigned num_words = CEIL (num_bytes, UNITS_PER_WORD);

  if (*cum <= 5 && *cum + num_words > 5)
    error ("too many function arguments for eBPF");

  *cum += num_words;
}

#undef TARGET_FUNCTION_ARG_ADVANCE
#define TARGET_FUNCTION_ARG_ADVANCE bpf_function_arg_advance

/* Output the assembly code for a constructor.  Since eBPF doesn't
   support indirect calls, constructors are not supported.  */

static void
bpf_output_constructor (rtx symbol, int priority ATTRIBUTE_UNUSED)
{
  tree decl = SYMBOL_REF_DECL (symbol);

  if (decl)
    sorry_at (DECL_SOURCE_LOCATION (decl),
	      "no constructors");
  else
    sorry ("no constructors");
}

#undef TARGET_ASM_CONSTRUCTOR
#define TARGET_ASM_CONSTRUCTOR bpf_output_constructor

/* Output the assembly code for a destructor.  Since eBPF doesn't
   support indirect calls, destructors are not supported.  */

static void
bpf_output_destructor (rtx symbol, int priority ATTRIBUTE_UNUSED)
{
  tree decl = SYMBOL_REF_DECL (symbol);

  if (decl)
    sorry_at (DECL_SOURCE_LOCATION (decl),
	      "no destructors");
  else
    sorry ("no destructors");
}

#undef TARGET_ASM_DESTRUCTOR
#define TARGET_ASM_DESTRUCTOR bpf_output_destructor

/* Return the appropriate instruction to CALL to a function.  TARGET
   is an RTX denoting the address of the called function.

   The main purposes of this function are:
   - To reject indirect CALL instructions, which are not supported by
     eBPF.
   - To recognize calls to kernel helper functions and emit the
     corresponding CALL N instruction.

   This function is called from the expansion of the 'call' pattern in
   bpf.md.  */

const char *
bpf_output_call (rtx target)
{
  rtx xops[1];

  switch (GET_CODE (target))
    {
    case CONST_INT:
      output_asm_insn ("call\t%0", &target);
      break;
    case SYMBOL_REF:
      {
	tree decl = SYMBOL_REF_DECL (target);
	tree attr;

	if (decl
	    && (attr = lookup_attribute ("kernel_helper",
					 DECL_ATTRIBUTES (decl))))
	  {
	    tree attr_args = TREE_VALUE (attr);

	    xops[0] = GEN_INT (TREE_INT_CST_LOW (TREE_VALUE (attr_args)));
	    output_asm_insn ("call\t%0", xops);
	  }
	else
	  output_asm_insn ("call\t%0", &target);

	break;
      }
    default:
      if (TARGET_XBPF)
	output_asm_insn ("call\t%0", &target);
      else
	{
	  error ("indirect call in function, which are not supported by eBPF");
	  output_asm_insn ("call 0", NULL);
	}
      break;
    }

  return "";
}

/* Print an instruction operand.  This function is called in the macro
   PRINT_OPERAND defined in bpf.h */

void
bpf_print_operand (FILE *file, rtx op, int code ATTRIBUTE_UNUSED)
{
  switch (GET_CODE (op))
    {
    case REG:
      fprintf (file, "%s", reg_names[REGNO (op)]);
      break;
    case MEM:
      output_address (GET_MODE (op), XEXP (op, 0));
      break;
    case CONST_DOUBLE:
      if (CONST_DOUBLE_HIGH (op))
	fprintf (file, HOST_WIDE_INT_PRINT_DOUBLE_HEX,
		 CONST_DOUBLE_HIGH (op), CONST_DOUBLE_LOW (op));
      else if (CONST_DOUBLE_LOW (op) < 0)
	fprintf (file, HOST_WIDE_INT_PRINT_HEX, CONST_DOUBLE_LOW (op));
      else
	fprintf (file, HOST_WIDE_INT_PRINT_DEC, CONST_DOUBLE_LOW (op));
      break;
    default:
      output_addr_const (file, op);
    }
}

/* Print an operand which is an address.  This function should handle
   any legit address, as accepted by bpf_legitimate_address_p, and
   also addresses that are valid in CALL instructions.

   This function is called in the PRINT_OPERAND_ADDRESS macro defined
   in bpf.h */

void
bpf_print_operand_address (FILE *file, rtx addr)
{
  switch (GET_CODE (addr))
    {
    case REG:
      fprintf (file, "[%s+0]", reg_names[REGNO (addr)]);
      break;
    case PLUS:
      {
	rtx op0 = XEXP (addr, 0);
	rtx op1 = XEXP (addr, 1);

	if (GET_CODE (op0) == REG && GET_CODE (op1) == CONST_INT)
	  {
	    fprintf (file, "[%s+", reg_names[REGNO (op0)]);
	    output_addr_const (file, op1);
	    fputs ("]", file);
	  }
	else
	  fatal_insn ("invalid address in operand", addr);
	break;
      }
    case MEM:
      /* Fallthrough.  */
    case LABEL_REF:
      /* Fallthrough.  */
      fatal_insn ("unsupported operand", addr);
      break;
    default:
      output_addr_const (file, addr);
      break;
    }
}

/* Add a BPF builtin function with NAME, CODE and TYPE.  Return
   the function decl or NULL_TREE if the builtin was not added.  */

static tree
def_builtin (const char *name, enum bpf_builtins code, tree type)
{
  tree t
    = add_builtin_function (name, type, code, BUILT_IN_MD, NULL, NULL_TREE);

  bpf_builtins[code] = t;
  return t;
}

/* Define machine-specific built-in functions.  */

static void
bpf_init_builtins (void)
{
  tree ullt = long_long_unsigned_type_node;

  /* Built-ins for BPF_LD_ABS and BPF_LD_IND instructions.  */

  def_builtin ("__builtin_bpf_load_byte", BPF_BUILTIN_LOAD_BYTE,
	       build_function_type_list (ullt, ullt, 0));
  def_builtin ("__builtin_bpf_load_half", BPF_BUILTIN_LOAD_HALF,
	       build_function_type_list (ullt, ullt, 0));
  def_builtin ("__builtin_bpf_load_word", BPF_BUILTIN_LOAD_WORD,
	       build_function_type_list (ullt, ullt, 0));
  def_builtin ("__builtin_preserve_access_index",
	       BPF_BUILTIN_PRESERVE_ACCESS_INDEX,
	       build_function_type_list (ptr_type_node, ptr_type_node, 0));
  def_builtin ("__builtin_preserve_field_info",
	       BPF_BUILTIN_PRESERVE_FIELD_INFO,
	       build_function_type_list (unsigned_type_node, ptr_type_node, unsigned_type_node, 0));
}

#undef TARGET_INIT_BUILTINS
#define TARGET_INIT_BUILTINS bpf_init_builtins

static tree bpf_core_compute (tree, vec<unsigned int> *);
static int bpf_core_get_index (const tree);
static bool is_attr_preserve_access (tree);

/* BPF Compile Once - Run Everywhere (CO-RE) support. Construct a CO-RE
   relocation record for EXPR of kind KIND to be emitted in the .BTF.ext
   section. Does nothing if we are not targetting BPF CO-RE, or if the
   constructed relocation would be a no-op.  */

static void
maybe_make_core_relo (tree expr, enum btf_core_reloc_kind kind)
{
  /* If we are not targetting BPF CO-RE, do not make a relocation. We
     might not be generating any debug info at all.  */
  if (!TARGET_BPF_CORE)
    return;

  auto_vec<unsigned int, 16> accessors;
  tree container = bpf_core_compute (expr, &accessors);

  /* Any valid use of the builtin must have at least one access. Otherwise,
     there is nothing to record and nothing to do. This is primarily a
     guard against optimizations leading to unexpected expressions in the
     argument of the builtin. For example, if the builtin is used to read
     a field of a structure which can be statically determined to hold a
     constant value, the argument to the builtin will be optimized to that
     constant. This is OK, and means the builtin call is superfluous.
     e.g.
     struct S foo;
     foo.a = 5;
     int x = __preserve_access_index (foo.a);
     ... do stuff with x
     'foo.a' in the builtin argument will be optimized to '5' with -01+.
     This sequence does not warrant recording a CO-RE relocation.  */

  if (accessors.length () < 1)
    return;
  accessors.reverse ();

  rtx_code_label *label = gen_label_rtx ();
  LABEL_PRESERVE_P (label) = 1;
  emit_label (label);

  /* Determine what output section this relocation will apply to.
     If this function is associated with a section, use that. Otherwise,
     fall back on '.text'.  */
  const char * section_name;
  if (current_function_decl && DECL_SECTION_NAME (current_function_decl))
    section_name = DECL_SECTION_NAME (current_function_decl);
  else
    section_name = ".text";

  /* Add the CO-RE relocation information to the BTF container.  */
  bpf_core_reloc_add (TREE_TYPE (container), section_name, &accessors, label,
		      kind);
}

/* Expand a call to __builtin_preserve_field_info by evaluating the requested
   information about SRC according to KIND, and return a tree holding
   the result.  */

static tree
bpf_core_field_info (tree src, enum btf_core_reloc_kind kind)
{
  unsigned int result;
  poly_int64 bitsize, bitpos;
  tree var_off = NULL_TREE;
  machine_mode mode;
  int unsignedp, reversep, volatilep;
  location_t loc = EXPR_LOCATION (src);

  get_inner_reference (src, &bitsize, &bitpos, &var_off, &mode, &unsignedp,
		       &reversep, &volatilep);

  /* Note: Use DECL_BIT_FIELD_TYPE rather than DECL_BIT_FIELD here, because it
     remembers whether the field in question was originally declared as a
     bitfield, regardless of how it has been optimized.  */
  bool bitfieldp = (TREE_CODE (src) == COMPONENT_REF
		    && DECL_BIT_FIELD_TYPE (TREE_OPERAND (src, 1)));

  unsigned int align = TYPE_ALIGN (TREE_TYPE (src));
  if (TREE_CODE (src) == COMPONENT_REF)
    {
      tree field = TREE_OPERAND (src, 1);
      if (DECL_BIT_FIELD_TYPE (field))
	align = TYPE_ALIGN (DECL_BIT_FIELD_TYPE (field));
      else
	align = TYPE_ALIGN (TREE_TYPE (field));
    }

  unsigned int start_bitpos = bitpos & ~(align - 1);
  unsigned int end_bitpos = start_bitpos + align;

  switch (kind)
    {
    case BPF_RELO_FIELD_BYTE_OFFSET:
      {
	if (var_off != NULL_TREE)
	  {
	    error_at (loc, "unsupported variable field offset");
	    return error_mark_node;
	  }

	if (bitfieldp)
	  result = start_bitpos / 8;
	else
	  result = bitpos / 8;
      }
      break;

    case BPF_RELO_FIELD_BYTE_SIZE:
      {
	if (mode == BLKmode && bitsize == -1)
	  {
	    error_at (loc, "unsupported variable size field access");
	    return error_mark_node;
	  }

	if (bitfieldp)
	  {
	    /* To match LLVM behavior, byte size of bitfields is recorded as
	       the full size of the base type. A 3-bit bitfield of type int is
	       therefore recorded as having a byte size of 4 bytes. */
	    result = end_bitpos - start_bitpos;
	    if (result & (result - 1))
	      {
		error_at (loc, "unsupported field expression");
		return error_mark_node;
	      }
	    result = result / 8;
	  }
	else
	  result = bitsize / 8;
      }
      break;

    case BPF_RELO_FIELD_EXISTS:
      /* The field always exists at compile time.  */
      result = 1;
      break;

    case BPF_RELO_FIELD_SIGNED:
      result = !unsignedp;
      break;

    case BPF_RELO_FIELD_LSHIFT_U64:
    case BPF_RELO_FIELD_RSHIFT_U64:
      {
	if (mode == BLKmode && bitsize == -1)
	  {
	    error_at (loc, "unsupported variable size field access");
	    return error_mark_node;
	  }
	if (var_off != NULL_TREE)
	  {
	    error_at (loc, "unsupported variable field offset");
	    return error_mark_node;
	  }

	if (!bitfieldp)
	  {
	    if (bitsize > 64)
	      {
		error_at (loc, "field size too large");
		return error_mark_node;
	      }
	    result = 64 - bitsize;
	    break;
	  }

	if (end_bitpos - start_bitpos > 64)
	  {
	    error_at (loc, "field size too large");
	    return error_mark_node;
	  }

	if (kind == BPF_RELO_FIELD_LSHIFT_U64)
	  {
	    if (TARGET_BIG_ENDIAN)
	      result = bitpos + 64 - start_bitpos - align;
	    else
	      result = start_bitpos + 64 - bitpos - bitsize;
	  }
	else /* RSHIFT_U64 */
	  result = 64 - bitsize;
      }
      break;

    default:
      error ("invalid second argument to built-in function");
      return error_mark_node;
      break;
    }

  return build_int_cst (unsigned_type_node, result);
}

/* Expand a call to a BPF-specific built-in function that was set up
   with bpf_init_builtins.  */

static rtx
bpf_expand_builtin (tree exp, rtx target ATTRIBUTE_UNUSED,
		    rtx subtarget ATTRIBUTE_UNUSED,
		    machine_mode mode ATTRIBUTE_UNUSED,
		    int ignore ATTRIBUTE_UNUSED)
{
  tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
  int code = DECL_MD_FUNCTION_CODE (fndecl);

  if (code == BPF_BUILTIN_LOAD_BYTE
      || code == BPF_BUILTIN_LOAD_HALF
      || code == BPF_BUILTIN_LOAD_WORD)
    {
      /* Expand an indirect load from the sk_buff in the context.
	 There is just one argument to the builtin, which is the
	 offset.

	 We try first to expand a ldabs* instruction.  In case this
	 fails, we try a ldind* instruction.  */

      enum insn_code abs_icode
	= (code == BPF_BUILTIN_LOAD_BYTE ? CODE_FOR_ldabsb
	   : code == BPF_BUILTIN_LOAD_HALF ? CODE_FOR_ldabsh
	   : CODE_FOR_ldabsw);

      enum insn_code ind_icode
	= (code == BPF_BUILTIN_LOAD_BYTE ? CODE_FOR_ldindb
	   : code == BPF_BUILTIN_LOAD_HALF ? CODE_FOR_ldindh
	   : CODE_FOR_ldindw);

      tree offset_arg = CALL_EXPR_ARG (exp, 0);
      struct expand_operand ops[2];

      create_input_operand (&ops[0], expand_normal (offset_arg),
			    TYPE_MODE (TREE_TYPE (offset_arg)));
      create_input_operand (&ops[1], const0_rtx, SImode);

      if (!maybe_expand_insn (abs_icode, 2, ops)
	  && !maybe_expand_insn (ind_icode, 2, ops))
	{
	  error ("invalid argument to built-in function");
	  return gen_rtx_REG (ops[0].mode, BPF_R0);
	}

      /* The result of the load is in R0.  */
      return gen_rtx_REG (ops[0].mode, BPF_R0);
    }

  else if (code == -1)
    {
      /* A resolved overloaded __builtin_preserve_access_index.  */
      tree arg = CALL_EXPR_ARG (exp, 0);

      if (arg == NULL_TREE)
	return NULL_RTX;

      if (TREE_CODE (arg) == SSA_NAME)
	{
	  gimple *def_stmt = SSA_NAME_DEF_STMT (arg);

	  if (is_gimple_assign (def_stmt))
	    arg = gimple_assign_rhs1 (def_stmt);
	  else
	    return expand_normal (arg);
	}

      /* Avoid double-recording information if the argument is an access to
	 a struct/union marked __attribute__((preserve_access_index)). This
	 Will be handled by the attribute handling pass.  */
      if (!is_attr_preserve_access (arg))
	maybe_make_core_relo (arg, BPF_RELO_FIELD_BYTE_OFFSET);

      return expand_normal (arg);
    }

  else if (code == -2)
    {
      /* A resolved overloaded __builtin_preserve_field_info.  */
      tree src = CALL_EXPR_ARG (exp, 0);
      tree kind_tree = CALL_EXPR_ARG (exp, 1);
      unsigned HOST_WIDE_INT kind_val;
      if (tree_fits_uhwi_p (kind_tree))
	kind_val = tree_to_uhwi (kind_tree);
      else
	error ("invalid argument to built-in function");

      enum btf_core_reloc_kind kind = (enum btf_core_reloc_kind) kind_val;

      if (TREE_CODE (src) == SSA_NAME)
	{
	  gimple *def_stmt = SSA_NAME_DEF_STMT (src);
	  if (is_gimple_assign (def_stmt))
	    src = gimple_assign_rhs1 (def_stmt);
	}
      if (TREE_CODE (src) == ADDR_EXPR)
	src = TREE_OPERAND (src, 0);

      tree result = bpf_core_field_info (src, kind);

      if (result != error_mark_node)
	maybe_make_core_relo (src, kind);

      return expand_normal (result);
    }

  gcc_unreachable ();
}

#undef TARGET_EXPAND_BUILTIN
#define TARGET_EXPAND_BUILTIN bpf_expand_builtin

/* Initialize target-specific function library calls.  This is mainly
   used to call library-provided soft-fp operations, since eBPF
   doesn't support floating-point in "hardware".  */

static void
bpf_init_libfuncs (void)
{
  set_conv_libfunc (sext_optab, DFmode, SFmode,
		    "__bpf_extendsfdf2");
  set_conv_libfunc (trunc_optab, SFmode, DFmode,
		    "__bpf_truncdfsf2");
  set_conv_libfunc (sfix_optab, SImode, DFmode,
		    "__bpf_fix_truncdfsi");
  set_conv_libfunc (sfloat_optab, DFmode, SImode,
		    "__bpf_floatsidf");
  set_conv_libfunc (ufloat_optab, DFmode, SImode,
		    "__bpf_floatunsidf");
}

#undef TARGET_INIT_LIBFUNCS
#define TARGET_INIT_LIBFUNCS bpf_init_libfuncs

/* Define the mechanism that will be used for describing frame unwind
   information to the debugger.  In eBPF it is not possible to unwind
   frames.  */

static enum unwind_info_type
bpf_debug_unwind_info ()
{
  return UI_NONE;
}

#undef TARGET_DEBUG_UNWIND_INFO
#define TARGET_DEBUG_UNWIND_INFO bpf_debug_unwind_info

/* Output assembly directives to assemble data of various sized and
   alignments.  */

#undef TARGET_ASM_BYTE_OP
#define TARGET_ASM_BYTE_OP "\t.byte\t"
#undef TARGET_ASM_ALIGNED_HI_OP
#define TARGET_ASM_ALIGNED_HI_OP "\t.half\t"
#undef TARGET_ASM_ALIGNED_SI_OP
#define TARGET_ASM_ALIGNED_SI_OP "\t.word\t"
#undef TARGET_ASM_ALIGNED_DI_OP
#define TARGET_ASM_ALIGNED_DI_OP "\t.dword\t"


/* BPF Compile Once - Run Everywhere (CO-RE) support routines.

   BPF CO-RE is supported in two forms:
   - A target builtin, __builtin_preserve_access_index

     This builtin accepts a single argument. Any access to an aggregate data
     structure (struct, union or array) within the argument will be recorded by
     the CO-RE machinery, resulting in a relocation record being placed in the
     .BTF.ext section of the output.

     It is implemented in bpf_resolve_overloaded_builtin () and
     bpf_expand_builtin (), using the supporting routines below.

   - An attribute, __attribute__((preserve_access_index))

     This attribute can be applied to struct and union types. Any access to a
     type with this attribute will be recorded by the CO-RE machinery.

     The pass pass_bpf_core_attr, below, implements support for
     this attribute.  */

/* Traverse the subtree under NODE, which is expected to be some form of
   aggregate access the CO-RE machinery cares about (like a read of a member of
   a struct or union), collecting access indices for the components and storing
   them in the vector referenced by ACCESSORS.

   Return the ultimate (top-level) container of the aggregate access. In general,
   this will be a VAR_DECL or some kind of REF.

   Note that the accessors are computed *in reverse order* of how the BPF
   CO-RE machinery defines them. The vector needs to be reversed (or simply
   output in reverse order) for the .BTF.ext relocation information.  */

static tree
bpf_core_compute (tree node, vec<unsigned int> *accessors)
{

  if (TREE_CODE (node) == ADDR_EXPR)
    node = TREE_OPERAND (node, 0);

  else if (TREE_CODE (node) == INDIRECT_REF
	   || TREE_CODE (node) == POINTER_PLUS_EXPR)
    {
      accessors->safe_push (0);
      return TREE_OPERAND (node, 0);
    }

  while (1)
    {
      switch (TREE_CODE (node))
	{
	case COMPONENT_REF:
	  accessors->safe_push (bpf_core_get_index (TREE_OPERAND (node, 1)));
	  break;

	case ARRAY_REF:
	case ARRAY_RANGE_REF:
	  accessors->safe_push (bpf_core_get_index (node));
	  break;

	case MEM_REF:
	  accessors->safe_push (bpf_core_get_index (node));
	  if (TREE_CODE (TREE_OPERAND (node, 0)) == ADDR_EXPR)
	    node = TREE_OPERAND (TREE_OPERAND (node, 0), 0);
	  goto done;

	default:
	  goto done;
	}
      node = TREE_OPERAND (node, 0);
    }
 done:
  return node;

}

/* Compute the index of the NODE in its immediate container.
   NODE should be a FIELD_DECL (i.e. of struct or union), or an ARRAY_REF. */
static int
bpf_core_get_index (const tree node)
{
  enum tree_code code = TREE_CODE (node);

  if (code == FIELD_DECL)
    {
      /* Lookup the index from the BTF information.  Some struct/union members
	 may not be emitted in BTF; only the BTF container has enough
	 information to compute the correct index.  */
      int idx = bpf_core_get_sou_member_index (ctf_get_tu_ctfc (), node);
      if (idx >= 0)
	return idx;
    }

  else if (code == ARRAY_REF || code == ARRAY_RANGE_REF || code == MEM_REF)
    {
      /* For array accesses, the index is operand 1.  */
      tree index = TREE_OPERAND (node, 1);

      /* If the indexing operand is a constant, extracting is trivial.  */
      if (TREE_CODE (index) == INTEGER_CST && tree_fits_shwi_p (index))
	return tree_to_shwi (index);
    }

  return -1;
}

/* Synthesize a new builtin function declaration with signature TYPE.
   Used by bpf_resolve_overloaded_builtin to resolve calls to
   __builtin_preserve_access_index.  */

static tree
bpf_core_newdecl (tree type, bool is_pai)
{
  tree rettype;
  char name[80];
  static unsigned long pai_count = 0;
  static unsigned long pfi_count = 0;

  if (is_pai)
    {
      rettype = build_function_type_list (type, type, NULL);
      int len = snprintf (name, sizeof (name), "%s", "__builtin_pai_");
      len = snprintf (name + len, sizeof (name) - len, "%lu", pai_count++);
    }
  else
    {
      rettype = build_function_type_list (unsigned_type_node, type,
					  unsigned_type_node, NULL);
      int len = snprintf (name, sizeof (name), "%s", "__builtin_pfi_");
      len = snprintf (name + len, sizeof (name) - len, "%lu", pfi_count++);
    }

  return add_builtin_function_ext_scope (name, rettype, is_pai ? -1 : -2,
					 BUILT_IN_MD, NULL, NULL_TREE);
}

/* Return whether EXPR could access some aggregate data structure that
   BPF CO-RE support needs to know about.  */

static bool
bpf_core_is_maybe_aggregate_access (tree expr)
{
  switch (TREE_CODE (expr))
    {
    case COMPONENT_REF:
    case BIT_FIELD_REF:
    case ARRAY_REF:
    case ARRAY_RANGE_REF:
      return true;
    case ADDR_EXPR:
    case NOP_EXPR:
      return bpf_core_is_maybe_aggregate_access (TREE_OPERAND (expr, 0));
    default:
      return false;
    }
}

struct core_walk_data {
  location_t loc;
  tree arg;
};

/* Callback function used with walk_tree from bpf_resolve_overloaded_builtin.  */

static tree
bpf_core_walk (tree *tp, int *walk_subtrees, void *data)
{
  struct core_walk_data *dat = (struct core_walk_data *) data;
  bool is_pai = dat->arg == NULL_TREE;

  /* If this is a type, don't do anything. */
  if (TYPE_P (*tp))
    {
      *walk_subtrees = 0;
      return NULL_TREE;
    }

  /* Build a new function call to a resolved builtin for the desired operation.
     If this is a preserve_field_info call, pass along the argument to the
     resolved builtin call. */
  if (bpf_core_is_maybe_aggregate_access (*tp))
    {
      tree newdecl = bpf_core_newdecl (TREE_TYPE (*tp), is_pai);
      tree newcall;
      if (is_pai)
	newcall = build_call_expr_loc (dat->loc, newdecl, 1, *tp);
      else
	newcall = build_call_expr_loc (dat->loc, newdecl, 2, *tp, dat->arg);

      *tp = newcall;
      *walk_subtrees = 0;
    }

  return NULL_TREE;
}

/* Implement target hook small_register_classes_for_mode_p.  */

static bool
bpf_small_register_classes_for_mode_p (machine_mode mode)
{
  if (TARGET_XBPF)
    return 1;
  else
    /* Avoid putting function addresses in registers, as calling these
       is not supported in eBPF.  */
    return (mode != FUNCTION_MODE);
}

#undef TARGET_SMALL_REGISTER_CLASSES_FOR_MODE_P
#define TARGET_SMALL_REGISTER_CLASSES_FOR_MODE_P \
  bpf_small_register_classes_for_mode_p

/* Return whether EXPR is a valid first argument for a call to
   __builtin_preserve_field_info.  */

static bool
bpf_is_valid_preserve_field_info_arg (tree expr)
{
  switch (TREE_CODE (expr))
    {
    case COMPONENT_REF:
    case BIT_FIELD_REF:
    case ARRAY_REF:
    case ARRAY_RANGE_REF:
      return true;
    case NOP_EXPR:
      return bpf_is_valid_preserve_field_info_arg (TREE_OPERAND (expr, 0));
    case ADDR_EXPR:
      /* Do not accept ADDR_EXPRs like &foo.bar, but do accept accesses like
	 foo.baz where baz is an array.  */
      return (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE);
    default:
      return false;
    }
}

/* Implement TARGET_RESOLVE_OVERLOADED_BUILTIN (see gccint manual section
   Target Macros::Misc.).
   We use this for the __builtin_preserve_access_index builtin for CO-RE
   support.

   FNDECL is the declaration of the builtin, and ARGLIST is the list of
   arguments passed to it, and is really a vec<tree,_> *.

   In this case, the 'operation' implemented by the builtin is a no-op;
   the builtin is just a marker. So, the result is simply the argument.  */

static tree
bpf_resolve_overloaded_builtin (location_t loc, tree fndecl, void *arglist)
{
  bool is_pai = DECL_MD_FUNCTION_CODE (fndecl)
    == BPF_BUILTIN_PRESERVE_ACCESS_INDEX;
  bool is_pfi = DECL_MD_FUNCTION_CODE (fndecl)
    == BPF_BUILTIN_PRESERVE_FIELD_INFO;

  if (!is_pai && !is_pfi)
    return NULL_TREE;

  /* We only expect one argument, but it may be an arbitrarily-complicated
     statement-expression. */
  vec<tree, va_gc> *params = static_cast<vec<tree, va_gc> *> (arglist);
  unsigned n_params = params ? params->length() : 0;

  if ((is_pai && n_params != 1) || (is_pfi && n_params != 2))
    {
      error_at (loc, "wrong number of arguments");
      return error_mark_node;
    }

  tree param = (*params)[0];

  /* If not generating BPF_CORE information, preserve_access_index does nothing,
     and simply "resolves to" the argument.  */
  if (!TARGET_BPF_CORE && is_pai)
    return param;

  if (is_pfi && !bpf_is_valid_preserve_field_info_arg (param))
    {
      error_at (EXPR_LOC_OR_LOC (param, loc),
		"argument is not a field access");
      return error_mark_node;
    }

  /* Do remove_c_maybe_const_expr for the arg.
     TODO: WHY do we have to do this here? Why doesn't c-typeck take care
     of it before or after this hook? */
  if (TREE_CODE (param) == C_MAYBE_CONST_EXPR)
    param = C_MAYBE_CONST_EXPR_EXPR (param);

  /* Construct a new function declaration with the correct type, and return
     a call to it.

     Calls with statement-expressions, for example:
     _(({ foo->a = 1; foo->u[2].b = 2; }))
     require special handling.

     We rearrange this into a new block scope in which each statement
     becomes a unique builtin call:
     {
       _ ({ foo->a = 1;});
       _ ({ foo->u[2].b = 2;});
     }

     This ensures that all the relevant information remains within the
     expression trees the builtin finally gets.  */

  struct core_walk_data data;
  data.loc = loc;
  data.arg = is_pai ? NULL_TREE : (*params)[1];

  walk_tree (&param, bpf_core_walk, (void *) &data, NULL);

  return param;
}

#undef TARGET_RESOLVE_OVERLOADED_BUILTIN
#define TARGET_RESOLVE_OVERLOADED_BUILTIN bpf_resolve_overloaded_builtin


/* Handling for __attribute__((preserve_access_index)) for BPF CO-RE support.

   This attribute marks a structure/union/array type as "preseve", so that
   every access to that type should be recorded and replayed by the BPF loader;
   this is just the same functionality as __builtin_preserve_access_index,
   but in the form of an attribute for an entire aggregate type.

   Note also that nested structs behave as though they all have the attribute.
   For example:
     struct X { int a; };
     struct Y { struct X bar} __attribute__((preserve_access_index));
     struct Y foo;
     foo.bar.a;
   will record access all the way to 'a', even though struct X does not have
   the preserve_access_index attribute.

   This is to follow LLVM behavior.

   This pass finds all accesses to objects of types marked with the attribute,
   and wraps them in the same "low-level" builtins used by the builtin version.
   All logic afterwards is therefore identical to the builtin version of
   preserve_access_index.  */

/* True iff tree T accesses any member of a struct/union/class which is marked
   with the PRESERVE_ACCESS_INDEX attribute.  */

static bool
is_attr_preserve_access (tree t)
{
  if (t == NULL_TREE)
    return false;

  poly_int64 bitsize, bitpos;
  tree var_off;
  machine_mode mode;
  int sign, reverse, vol;

  tree base = get_inner_reference (t, &bitsize, &bitpos, &var_off, &mode,
				   &sign, &reverse, &vol);

  if (TREE_CODE (base) == MEM_REF)
    {
      return lookup_attribute ("preserve_access_index",
			       TYPE_ATTRIBUTES (TREE_TYPE (base)));
    }

  if (TREE_CODE (t) == COMPONENT_REF)
    {
      /* preserve_access_index propegates into nested structures,
	 so check whether this is a component of another component
	 which in turn is part of such a struct.  */

      const tree op = TREE_OPERAND (t, 0);

      if (TREE_CODE (op) == COMPONENT_REF)
	return is_attr_preserve_access (op);

      const tree container = DECL_CONTEXT (TREE_OPERAND (t, 1));

      return lookup_attribute ("preserve_access_index",
			       TYPE_ATTRIBUTES (container));
    }

  else if (TREE_CODE (t) == ADDR_EXPR)
    return is_attr_preserve_access (TREE_OPERAND (t, 0));

  return false;
}

/* The body of pass_bpf_core_attr. Scan RTL for accesses to structs/unions
   marked with __attribute__((preserve_access_index)) and generate a CO-RE
   relocation for any such access.  */

static void
handle_attr_preserve (function *fn)
{
  basic_block bb;
  rtx_insn *insn;
  rtx_code_label *label;
  FOR_EACH_BB_FN (bb, fn)
    {
      FOR_BB_INSNS (bb, insn)
	{
	  if (!NONJUMP_INSN_P (insn))
	    continue;
	  rtx pat = PATTERN (insn);
	  if (GET_CODE (pat) != SET)
	    continue;

	  start_sequence();

	  for (int i = 0; i < 2; i++)
	    {
	      rtx mem = XEXP (pat, i);
	      if (MEM_P (mem))
		{
		  tree expr = MEM_EXPR (mem);
		  if (!expr)
		    continue;

		  if (TREE_CODE (expr) == MEM_REF
		      && TREE_CODE (TREE_OPERAND (expr, 0)) == SSA_NAME)
		    {
		      gimple *def_stmt = SSA_NAME_DEF_STMT (TREE_OPERAND (expr, 0));
		      if (def_stmt && is_gimple_assign (def_stmt))
			expr = gimple_assign_rhs1 (def_stmt);
		    }

		  if (is_attr_preserve_access (expr))
		    {
		      auto_vec<unsigned int, 16> accessors;
		      tree container = bpf_core_compute (expr, &accessors);
		      if (accessors.length () < 1)
			continue;
		      accessors.reverse ();

		      container = TREE_TYPE (container);
		      const char * section_name;
		      if (DECL_SECTION_NAME (fn->decl))
			section_name = DECL_SECTION_NAME (fn->decl);
		      else
			section_name = ".text";

		      label = gen_label_rtx ();
		      LABEL_PRESERVE_P (label) = 1;
		      emit_label (label);

		      /* Add the CO-RE relocation information to the BTF container.  */
		      bpf_core_reloc_add (container, section_name, &accessors, label,
					  BPF_RELO_FIELD_BYTE_OFFSET);
		    }
		}
	    }
	  rtx_insn *seq = get_insns ();
	  end_sequence ();
	  emit_insn_before (seq, insn);
	}
    }
}


/* This pass finds accesses to structures marked with the BPF target attribute
   __attribute__((preserve_access_index)). For every such access, a CO-RE
   relocation record is generated, to be output in the .BTF.ext section.  */

namespace {

const pass_data pass_data_bpf_core_attr =
{
  RTL_PASS, /* type */
  "bpf_core_attr", /* name */
  OPTGROUP_NONE, /* optinfo_flags */
  TV_NONE, /* tv_id */
  0, /* properties_required */
  0, /* properties_provided */
  0, /* properties_destroyed */
  0, /* todo_flags_start */
  0, /* todo_flags_finish */
};

class pass_bpf_core_attr : public rtl_opt_pass
{
public:
  pass_bpf_core_attr (gcc::context *ctxt)
    : rtl_opt_pass (pass_data_bpf_core_attr, ctxt)
  {}

  virtual bool gate (function *) { return TARGET_BPF_CORE; }
  virtual unsigned int execute (function *);
};

unsigned int
pass_bpf_core_attr::execute (function *fn)
{
  handle_attr_preserve (fn);
  return 0;
}

} /* Anonymous namespace.  */

rtl_opt_pass *
make_pass_bpf_core_attr (gcc::context *ctxt)
{
  return new pass_bpf_core_attr (ctxt);
}

/* Finally, build the GCC target.  */

struct gcc_target targetm = TARGET_INITIALIZER;

#include "gt-bpf.h"