File: DIMemoryUseCollector.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (2136 lines) | stat: -rw-r--r-- 79,651 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
//===--- DIMemoryUseCollector.cpp -----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "definite-init"

#include "DIMemoryUseCollector.h"
#include "swift/AST/Expr.h"
#include "swift/SIL/ApplySite.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SILOptimizer/Utils/DistributedActor.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/SaveAndRestore.h"

using namespace swift;
using namespace ownership;

//===----------------------------------------------------------------------===//
//                                  Utility
//===----------------------------------------------------------------------===//

static bool isVariableOrResult(MarkUninitializedInst *MUI) {
  return MUI->isVar() || MUI->isOut();
}

static void gatherDestroysOfContainer(const DIMemoryObjectInfo &memoryInfo,
                                      DIElementUseInfo &useInfo) {
  auto *uninitMemory = memoryInfo.getUninitializedValue();

  // The uninitMemory must be used on an alloc_box, alloc_stack, or global_addr.
  // If we have an alloc_stack or a global_addr, there is nothing further to do.
  if (isa<AllocStackInst>(uninitMemory->getOperand(0)) ||
      isa<GlobalAddrInst>(uninitMemory->getOperand(0)) ||
      isa<SILArgument>(uninitMemory->getOperand(0)) ||
      // FIXME: We only support pointer to address here to not break LLDB. It is
      // important that long term we get rid of this since this is a situation
      // where LLDB is breaking SILGen/DI invariants by not creating a new
      // independent stack location for the pointer to address.
      isa<PointerToAddressInst>(uninitMemory->getOperand(0))) {
    return;
  }

  // Otherwise, we assume that we have an alloc_box. Treat destroys of the
  // alloc_box as load+destroys of the value stored in the box.
  //
  // TODO: This should really be tracked separately from other destroys so that
  // we distinguish the lifetime of the container from the value itself.
  assert(isa<ProjectBoxInst>(uninitMemory));
  auto value = uninitMemory->getOperand(0);
  if (auto *bbi = dyn_cast<BeginBorrowInst>(value)) {
    value = bbi->getOperand();
  }
  auto *mui = cast<MarkUninitializedInst>(value);
  for (auto *user : mui->getUsersOfType<DestroyValueInst>()) {
    useInfo.trackDestroy(user);
  }
}

//===----------------------------------------------------------------------===//
//                     DIMemoryObjectInfo Implementation
//===----------------------------------------------------------------------===//

static unsigned getElementCountRec(TypeExpansionContext context,
                                   SILModule &Module, SILType T,
                                   bool IsSelfOfNonDelegatingInitializer) {
  // If this is a tuple, it is always recursively flattened.
  if (CanTupleType TT = T.getAs<TupleType>()) {
    assert(!IsSelfOfNonDelegatingInitializer && "self never has tuple type");
    unsigned NumElements = 0;
    for (unsigned i = 0, e = TT->getNumElements(); i < e; ++i)
      NumElements +=
          getElementCountRec(context, Module, T.getTupleElementType(i), false);
    return NumElements;
  }

  // If this is the top level of a 'self' value, we flatten structs and classes.
  // Stored properties with tuple types are tracked with independent lifetimes
  // for each of the tuple members.
  if (IsSelfOfNonDelegatingInitializer) {
    // Protocols never have a stored properties.
    if (auto *NTD = T.getNominalOrBoundGenericNominal()) {
      unsigned NumElements = 0;
      for (auto *VD : NTD->getStoredProperties())
        NumElements += getElementCountRec(
            context, Module, T.getFieldType(VD, Module, context), false);
      for (auto *P : NTD->getInitAccessorProperties()) {
        auto *init = P->getAccessor(AccessorKind::Init);
        if (init->getInitializedProperties().empty())
          ++NumElements;
      }
      return NumElements;
    }
  }

  // Otherwise, it is a single element.
  return 1;
}

static std::pair<SILType, bool>
computeMemorySILType(MarkUninitializedInst *MUI, SILValue Address) {
  // Compute the type of the memory object.
  SILType MemorySILType = Address->getType().getObjectType();

  // If this is a let variable we're initializing, remember this so we don't
  // allow reassignment.
  if (!isVariableOrResult(MUI))
    return {MemorySILType, false};

  auto *VDecl = MUI->getLoc().getAsASTNode<VarDecl>();
  if (!VDecl)
    return {MemorySILType, false};

  return {MemorySILType, VDecl->isLet()};
}

DIMemoryObjectInfo::DIMemoryObjectInfo(MarkUninitializedInst *MI)
    : MemoryInst(MI) {
  auto &Module = MI->getModule();

  SILValue Address = MemoryInst;
  if (auto BBI = MemoryInst->getSingleUserOfType<BeginBorrowInst>()) {
    if (auto PBI = BBI->getSingleUserOfType<ProjectBoxInst>()) {
      IsBox = true;
      Address = PBI;
    }
  }
  if (auto PBI = MemoryInst->getSingleUserOfType<ProjectBoxInst>()) {
    IsBox = true;
    Address = PBI;
  }

  std::tie(MemorySILType, IsLet) = computeMemorySILType(MI, Address);

  // Compute the number of elements to track in this memory object.
  // If this is a 'self' in a delegating initializer, we only track one bit:
  // whether self.init is called or not.
  if (isDelegatingInit()) {
    NumElements = 1;
    return;
  }

  // If this is a derived class init method for which stored properties are
  // separately initialized, track an element for the super.init call.
  if (isDerivedClassSelfOnly()) {
    NumElements = 1;
    return;
  }

  // Otherwise, we break down the initializer.
  NumElements =
      getElementCountRec(TypeExpansionContext(*MI->getFunction()), Module,
                         MemorySILType, isNonDelegatingInit());

  // If this is a derived class init method, track an extra element to determine
  // whether super.init has been called at each program point.
  NumElements += unsigned(isDerivedClassSelf());

  // Make sure we track /something/ in a cross-module struct initializer.
  if (NumElements == 0 && isCrossModuleStructInitSelf()) {
    NumElements = 1;
    HasDummyElement = true;
  }
}

SILInstruction *DIMemoryObjectInfo::getFunctionEntryPoint() const {
  return &*getFunction().begin()->begin();
}

static SingleValueInstruction *
getUninitializedValue(MarkUninitializedInst *MemoryInst) {
  SILValue inst = MemoryInst;
  if (auto *bbi = MemoryInst->getSingleUserOfType<BeginBorrowInst>()) {
    inst = bbi;
  }

  if (SingleValueInstruction *svi =
          inst->getSingleUserOfType<ProjectBoxInst>()) {
    return svi;
  }

  return MemoryInst;
}

SingleValueInstruction *DIMemoryObjectInfo::getUninitializedValue() const {
  return ::getUninitializedValue(MemoryInst);
}

/// Given a symbolic element number, return the type of the element.
static SILType getElementTypeRec(TypeExpansionContext context,
                                 SILModule &Module, SILType T, unsigned EltNo,
                                 bool IsSelfOfNonDelegatingInitializer) {
  // If this is a tuple type, walk into it.
  if (CanTupleType TT = T.getAs<TupleType>()) {
    assert(!IsSelfOfNonDelegatingInitializer && "self never has tuple type");
    for (unsigned i = 0, e = TT->getNumElements(); i < e; ++i) {
      auto FieldType = T.getTupleElementType(i);
      unsigned NumFieldElements =
          getElementCountRec(context, Module, FieldType, false);
      if (EltNo < NumFieldElements)
        return getElementTypeRec(context, Module, FieldType, EltNo, false);
      EltNo -= NumFieldElements;
    }
    // This can only happen if we look at a symbolic element number of an empty
    // tuple.
    llvm::report_fatal_error("invalid element number");
  }

  // If this is the top level of a 'self' value, we flatten structs and classes.
  // Stored properties with tuple types are tracked with independent lifetimes
  // for each of the tuple members.
  if (IsSelfOfNonDelegatingInitializer) {
    if (auto *NTD = T.getNominalOrBoundGenericNominal()) {
      bool HasStoredProperties = false;
      for (auto *VD : NTD->getStoredProperties()) {
        HasStoredProperties = true;
        auto FieldType = T.getFieldType(VD, Module, context);
        unsigned NumFieldElements =
            getElementCountRec(context, Module, FieldType, false);
        if (EltNo < NumFieldElements)
          return getElementTypeRec(context, Module, FieldType, EltNo, false);
        EltNo -= NumFieldElements;
      }

      // If we do not have any stored properties and were passed an EltNo of 0,
      // just return self.
      if (!HasStoredProperties && EltNo == 0) {
        return T;
      }
      llvm::report_fatal_error("invalid element number");
    }
  }

  // Otherwise, it is a leaf element.
  assert(EltNo == 0);
  return T;
}

/// getElementTypeRec - Return the swift type of the specified element.
SILType DIMemoryObjectInfo::getElementType(unsigned EltNo) const {
  auto &Module = MemoryInst->getModule();
  return getElementTypeRec(TypeExpansionContext(*MemoryInst->getFunction()),
                           Module, MemorySILType, EltNo, isNonDelegatingInit());
}

/// During tear-down of a distributed actor, we must invoke its
/// \p actorSystem.resignID method, passing in the \p id from the
/// instance. Thus, this function inspects the VarDecl about to be destroyed
/// and if it matches the \p id, the \p resignIdentity call is emitted.
///
/// NOTE (id-before-actorSystem): it is crucial that the \p id is
/// deinitialized before the \p actorSystem is deinitialized, because
/// resigning the identity requires a call into the \p actorSystem.
/// Since deinitialization consistently happens in-order, according to the
/// listing returned by \p NominalTypeDecl::getStoredProperties
/// it is important the VarDecl for the \p id is synthesized before
/// the \p actorSystem so that we get the right ordering in DI and deinits.
///
/// \param nomDecl a distributed actor decl
/// \param var a VarDecl that is a member of the \p nomDecl
static void tryToResignIdentity(SILLocation loc, SILBuilder &B,
                                NominalTypeDecl* nomDecl, VarDecl *var,
                                SILValue idRef, SILValue actorInst) {
  assert(nomDecl->isDistributedActor());

  if (var != nomDecl->getDistributedActorIDProperty())
    return;

  emitResignIdentityCall(B, loc, cast<ClassDecl>(nomDecl),
                         actorInst, idRef);
}

/// Given a tuple element number (in the flattened sense) return a pointer to a
/// leaf element of the specified number, so we can insert destroys for it.
SILValue DIMemoryObjectInfo::emitElementAddressForDestroy(
    unsigned EltNo, SILLocation Loc, SILBuilder &B,
    SmallVectorImpl<std::pair<SILValue, EndScopeKind>> &EndScopeList) const {
  SILValue Ptr = getUninitializedValue();
  bool IsSelf = isNonDelegatingInit();
  auto &Module = MemoryInst->getModule();

  auto PointeeType = MemorySILType;

  while (1) {
    // If we have a tuple, flatten it.
    if (CanTupleType TT = PointeeType.getAs<TupleType>()) {
      assert(!IsSelf && "self never has tuple type");

      // Figure out which field we're walking into.
      unsigned FieldNo = 0;
      for (unsigned i = 0, e = TT->getNumElements(); i < e; ++i) {
        auto EltTy = PointeeType.getTupleElementType(i);
        unsigned NumSubElt = getElementCountRec(
            TypeExpansionContext(B.getFunction()), Module, EltTy, false);
        if (EltNo < NumSubElt) {
          Ptr = B.createTupleElementAddr(Loc, Ptr, FieldNo);
          PointeeType = EltTy;
          break;
        }

        EltNo -= NumSubElt;
        ++FieldNo;
      }
      continue;
    }

    // If this is the top level of a 'self' value, we flatten structs and
    // classes.  Stored properties with tuple types are tracked with independent
    // lifetimes for each of the tuple members.
    if (IsSelf) {
      if (auto *NTD = PointeeType.getNominalOrBoundGenericNominal()) {
        const bool IsDistributedActor = NTD->isDistributedActor();
        bool HasStoredProperties = false;
        for (auto *VD : NTD->getStoredProperties()) {
          if (!HasStoredProperties) {
            HasStoredProperties = true;
            // If we have a class, we can use a borrow directly and avoid ref
            // count traffic.
            if (isa<ClassDecl>(NTD) && Ptr->getType().isAddress()) {
              SILValue Borrowed = Ptr = B.createLoadBorrow(Loc, Ptr);
              EndScopeList.emplace_back(Borrowed, EndScopeKind::Borrow);
            }
          }
          auto expansionContext = TypeExpansionContext(B.getFunction());
          auto FieldType =
              PointeeType.getFieldType(VD, Module, expansionContext);
          unsigned NumFieldElements =
              getElementCountRec(expansionContext, Module, FieldType, false);
          if (EltNo < NumFieldElements) {
            if (isa<StructDecl>(NTD)) {
              Ptr = B.createStructElementAddr(Loc, Ptr, VD);
            } else {
              assert(isa<ClassDecl>(NTD));
              SILValue Original, Borrowed;
              if (Ptr->getOwnershipKind() != OwnershipKind::Guaranteed) {
                Original = Ptr;
                Borrowed = Ptr = B.createBeginBorrow(Loc, Ptr);
                EndScopeList.emplace_back(Borrowed, EndScopeKind::Borrow);
              }
              SILValue Self = Ptr;
              Ptr = B.createRefElementAddr(Loc, Ptr, VD);
              Ptr = B.createBeginAccess(
                  Loc, Ptr, SILAccessKind::Deinit, SILAccessEnforcement::Static,
                  false /*noNestedConflict*/, false /*fromBuiltin*/);

              if (IsDistributedActor)
                tryToResignIdentity(Loc, B, NTD, VD, Ptr, Self);

              EndScopeList.emplace_back(Ptr, EndScopeKind::Access);
            }

            PointeeType = FieldType;
            IsSelf = false;
            break;
          }
          EltNo -= NumFieldElements;
        }

        if (!HasStoredProperties) {
          assert(EltNo == 0 && "Element count problem");
          return Ptr;
        }

        continue;
      }
    }

    // Have we gotten to our leaf element?
    assert(EltNo == 0 && "Element count problem");
    return Ptr;
  }
}

/// Push the symbolic path name to the specified element number onto the
/// specified std::string.
static void getPathStringToElementRec(TypeExpansionContext context,
                                      SILModule &Module, SILType T,
                                      unsigned EltNo, std::string &Result) {
  CanTupleType TT = T.getAs<TupleType>();
  if (!TT) {
    // Otherwise, there are no subelements.
    assert(EltNo == 0 && "Element count problem");
    return;
  }

  unsigned FieldNo = 0;
  for (unsigned i = 0, e = TT->getNumElements(); i < e; ++i) {
    auto Field = TT->getElement(i);
    SILType FieldTy = T.getTupleElementType(i);
    unsigned NumFieldElements = getElementCountRec(context, Module, FieldTy, false);

    if (EltNo < NumFieldElements) {
      Result += '.';
      if (Field.hasName())
        Result += Field.getName().str();
      else
        Result += llvm::utostr(FieldNo);
      return getPathStringToElementRec(context, Module, FieldTy, EltNo, Result);
    }

    EltNo -= NumFieldElements;

    ++FieldNo;
  }

  llvm_unreachable("Element number is out of range for this type!");
}

ValueDecl *
DIMemoryObjectInfo::getPathStringToElement(unsigned Element,
                                           std::string &Result) const {
  auto &Module = MemoryInst->getModule();

  if (isAnyInitSelf())
    Result = "self";
  else if (ValueDecl *VD =
               dyn_cast_or_null<ValueDecl>(getLoc().getAsASTNode<Decl>()))
    Result = VD->hasName() ? VD->getBaseIdentifier().str() : "_";
  else
    Result = "<unknown>";

  // If this is indexing into a field of 'self', look it up.
  auto expansionContext = TypeExpansionContext(*MemoryInst->getFunction());
  if (isNonDelegatingInit() && !isDerivedClassSelfOnly()) {
    if (auto *NTD = MemorySILType.getNominalOrBoundGenericNominal()) {
      bool HasStoredProperty = false;
      for (auto *VD : NTD->getStoredProperties()) {
        HasStoredProperty = true;
        auto FieldType =
            MemorySILType.getFieldType(VD, Module, expansionContext);
        unsigned NumFieldElements =
            getElementCountRec(expansionContext, Module, FieldType, false);
        if (Element < NumFieldElements) {
          Result += '.';
          auto originalProperty = VD->getOriginalWrappedProperty();
          if (originalProperty) {
            Result += originalProperty->getName().str();
          } else {
            Result += VD->getName().str();
          }
          getPathStringToElementRec(expansionContext, Module, FieldType,
                                    Element, Result);
          return VD;
        }
        Element -= NumFieldElements;
      }

      for (auto *property : NTD->getInitAccessorProperties()) {
        auto *init = property->getAccessor(AccessorKind::Init);
        if (init->getInitializedProperties().empty()) {
          if (Element == 0)
            return property;
          --Element;
        }
      }

      // If we do not have any stored properties, we have nothing of interest.
      if (!HasStoredProperty)
        return nullptr;
    }
  }

  // Get the path through a tuple, if relevant.
  getPathStringToElementRec(expansionContext, Module, MemorySILType, Element,
                            Result);

  // If we are analyzing a variable, we can generally get the decl associated
  // with it.
  if (isVariableOrResult(MemoryInst))
    return MemoryInst->getLoc().getAsASTNode<VarDecl>();

  // Otherwise, we can't.
  return nullptr;
}

/// If the specified value is a 'let' property in an initializer, return true.
bool DIMemoryObjectInfo::isElementLetProperty(unsigned Element) const {
  // If we aren't representing 'self' in a non-delegating initializer, then we
  // can't have 'let' properties.
  if (!isNonDelegatingInit())
    return IsLet;

  auto NTD = MemorySILType.getNominalOrBoundGenericNominal();

  if (!NTD) {
    // Otherwise, we miscounted elements?
    assert(Element == 0 && "Element count problem");
    return false;
  }

  auto &Module = MemoryInst->getModule();

  auto expansionContext = TypeExpansionContext(*MemoryInst->getFunction());
  for (auto *VD : NTD->getStoredProperties()) {
    auto FieldType = MemorySILType.getFieldType(VD, Module, expansionContext);
    unsigned NumFieldElements =
        getElementCountRec(expansionContext, Module, FieldType, false);
    if (Element < NumFieldElements)
      return VD->isLet();
    Element -= NumFieldElements;
  }

  for (auto *property : NTD->getInitAccessorProperties()) {
    auto *init = property->getAccessor(AccessorKind::Init);
    if (init->getInitializedProperties().empty()) {
      if (Element == 0)
        return !property->getAccessor(AccessorKind::Set);
      --Element;
    }
  }

  // Otherwise, we miscounted elements?
  assert(Element == 0 && "Element count problem");
  return false;
}

SingleValueInstruction *DIMemoryObjectInfo::findUninitializedSelfValue() const {
  // If the object is 'self', return its uninitialized value.
  if (isAnyInitSelf())
    return getUninitializedValue();

  // Otherwise we need to scan entry block to find mark_uninitialized
  // instruction that belongs to `self`.

  auto *BB = getFunction().getEntryBlock();
  if (!BB)
    return nullptr;

  for (auto &I : *BB) {
    SILInstruction *Inst = &I;
    if (auto *MUI = dyn_cast<MarkUninitializedInst>(Inst)) {
      // If instruction is not a local variable, it could only
      // be some kind of `self` (root, delegating, derived etc.)
      // see \c MarkUninitializedInst::Kind for more details.
      if (!isVariableOrResult(MUI))
        return ::getUninitializedValue(MUI);
    }
  }
  return nullptr;
}

ConstructorDecl *DIMemoryObjectInfo::getActorInitSelf() const {
  // is it 'self'?
  if (!isVariableOrResult(MemoryInst)) {
    if (auto decl =
        dyn_cast_or_null<ClassDecl>(getASTType()->getAnyNominal()))
      // is it for an actor?
      if (decl->isAnyActor())
        if (auto *silFn = MemoryInst->getFunction())
          // are we in a constructor?
          if (auto *ctor = dyn_cast_or_null<ConstructorDecl>(
                            silFn->getDeclContext()->getAsDecl()))
            return ctor;
  }

  return nullptr;
}

//===----------------------------------------------------------------------===//
//                        DIMemoryUse Implementation
//===----------------------------------------------------------------------===//

/// onlyTouchesTrivialElements - Return true if all of the accessed elements
/// have trivial type and the access itself is a trivial instruction.
bool DIMemoryUse::onlyTouchesTrivialElements(
    const DIMemoryObjectInfo &MI) const {
  // assign_by_wrapper calls functions to assign a value. This is not
  // considered as trivial.
  if (isa<AssignByWrapperInst>(Inst) || isa<AssignOrInitInst>(Inst))
    return false;

  auto *F = Inst->getFunction();

  for (unsigned i = FirstElement, e = i + NumElements; i != e; ++i) {
    // Skip 'super.init' bit
    if (i == MI.getNumMemoryElements())
      return false;

    auto EltTy = MI.getElementType(i);
    if (!EltTy.isTrivial(*F))
      return false;
  }
  return true;
}

//===----------------------------------------------------------------------===//
//                      DIElementUseInfo Implementation
//===----------------------------------------------------------------------===//

void DIElementUseInfo::trackStoreToSelf(SILInstruction *I) {
  StoresToSelf.push_back(I);
}

//===----------------------------------------------------------------------===//
//                     ElementUseCollector Implementation
//===----------------------------------------------------------------------===//

namespace {

/// Gathers information about a specific address and its uses to determine
/// definite initialization.
class ElementUseCollector {
public:
  typedef SmallPtrSet<SILFunction *, 8> FunctionSet;

private:
  SILModule &Module;
  const DIMemoryObjectInfo &TheMemory;
  DIElementUseInfo &UseInfo;
  FunctionSet &VisitedClosures;

  /// IsSelfOfNonDelegatingInitializer - This is true if we're looking at the
  /// top level of a 'self' variable in a non-delegating init method.
  bool IsSelfOfNonDelegatingInitializer;

  /// When walking the use list, if we index into a struct element, keep track
  /// of this, so that any indexes into tuple subelements don't affect the
  /// element we attribute an access to.
  bool InStructSubElement = false;

  /// When walking the use list, if we index into an enum slice, keep track
  /// of this.
  bool InEnumSubElement = false;

  /// If true, then encountered uses correspond to a VarDecl marked
  /// as \p @_compilerInitialized
  bool InCompilerInitializedField = false;

public:
  ElementUseCollector(const DIMemoryObjectInfo &TheMemory,
                      DIElementUseInfo &UseInfo,
                      FunctionSet &visitedClosures)
      : Module(TheMemory.getModule()), TheMemory(TheMemory), UseInfo(UseInfo),
        VisitedClosures(visitedClosures)
  {}

  /// This is the main entry point for the use walker.  It collects uses from
  /// the address and the refcount result of the allocation.
  void collectFrom(SILValue V, bool collectDestroysOfContainer) {
    IsSelfOfNonDelegatingInitializer = TheMemory.isNonDelegatingInit();

    // If this is a delegating initializer, collect uses specially.
    if (IsSelfOfNonDelegatingInitializer &&
        TheMemory.getASTType()->getClassOrBoundGenericClass() != nullptr) {
      assert(!TheMemory.isDerivedClassSelfOnly() &&
             "Should have been handled outside of here");
      // If this is a class pointer, we need to look through ref_element_addrs.
      collectClassSelfUses(V);
      return;
    }

    collectUses(V, 0);
    if (collectDestroysOfContainer) {
      assert(V == TheMemory.getUninitializedValue() &&
             "can only gather destroys of root value");
      gatherDestroysOfContainer(TheMemory, UseInfo);
    }
  }

  void trackUse(DIMemoryUse Use) { UseInfo.trackUse(Use); }

  void trackDestroy(SILInstruction *Destroy) { UseInfo.trackDestroy(Destroy); }

  /// Return the raw number of elements including the 'super.init' value.
  unsigned getNumMemoryElements() const { return TheMemory.getNumElements(); }

private:
  void collectUses(SILValue Pointer, unsigned BaseEltNo);
  bool addClosureElementUses(PartialApplyInst *pai, Operand *argUse);
  void collectAssignOrInitUses(AssignOrInitInst *pai, unsigned BaseEltNo = 0);

  void collectClassSelfUses(SILValue ClassPointer);
  void collectClassSelfUses(SILValue ClassPointer, SILType MemorySILType,
                            llvm::SmallDenseMap<VarDecl *, unsigned> &EN);

  void addElementUses(unsigned BaseEltNo, SILType UseTy, SILInstruction *User,
                      DIUseKind Kind, NullablePtr<VarDecl> Field = 0);
  void collectTupleElementUses(TupleElementAddrInst *TEAI, unsigned BaseEltNo);
  void collectStructElementUses(StructElementAddrInst *SEAI,
                                unsigned BaseEltNo);
};
} // end anonymous namespace

/// addElementUses - An operation (e.g. load, store, inout usec etc) on a value
/// acts on all of the aggregate elements in that value.  For example, a load
/// of $*(Int,Int) is a use of both Int elements of the tuple.  This is a helper
/// to keep the Uses data structure up to date for aggregate uses.
void ElementUseCollector::addElementUses(unsigned BaseEltNo, SILType UseTy,
                                         SILInstruction *User, DIUseKind Kind,
                                         NullablePtr<VarDecl> Field) {
  // If we're in a subelement of a struct or enum, just mark the struct, not
  // things that come after it in a parent tuple.
  unsigned NumElements = 1;
  if (TheMemory.getNumElements() != 1 && !InStructSubElement &&
      !InEnumSubElement)
    NumElements =
        getElementCountRec(TypeExpansionContext(*User->getFunction()), Module,
                           UseTy, IsSelfOfNonDelegatingInitializer);

  trackUse(DIMemoryUse(User, Kind, BaseEltNo, NumElements, Field));
}

/// Given a tuple_element_addr or struct_element_addr, compute the new
/// BaseEltNo implicit in the selected member, and recursively add uses of
/// the instruction.
void ElementUseCollector::collectTupleElementUses(TupleElementAddrInst *TEAI,
                                                  unsigned BaseEltNo) {

  // If we're walking into a tuple within a struct or enum, don't adjust the
  // BaseElt.  The uses hanging off the tuple_element_addr are going to be
  // counted as uses of the struct or enum itself.
  if (InStructSubElement || InEnumSubElement)
    return collectUses(TEAI, BaseEltNo);

  assert(!IsSelfOfNonDelegatingInitializer && "self doesn't have tuple type");

  // tuple_element_addr P, 42 indexes into the current tuple element.
  // Recursively process its uses with the adjusted element number.
  unsigned FieldNo = TEAI->getFieldIndex();
  auto T = TEAI->getOperand()->getType();
  if (T.is<TupleType>()) {
    for (unsigned i = 0; i != FieldNo; ++i) {
      SILType EltTy = T.getTupleElementType(i);
      BaseEltNo += getElementCountRec(TypeExpansionContext(*TEAI->getFunction()),
                                      Module, EltTy, false);
    }
  }

  collectUses(TEAI, BaseEltNo);
}

void ElementUseCollector::collectStructElementUses(StructElementAddrInst *SEAI,
                                                   unsigned BaseEltNo) {
  // Generally, we set the "InStructSubElement" flag and recursively process
  // the uses so that we know that we're looking at something within the
  // current element.
  if (!IsSelfOfNonDelegatingInitializer) {
    llvm::SaveAndRestore<bool> X(InStructSubElement, true);
    collectUses(SEAI, BaseEltNo);
    return;
  }

  // If this is the top level of 'self' in an init method, we treat each
  // element of the struct as an element to be analyzed independently.
  llvm::SaveAndRestore<bool> X(IsSelfOfNonDelegatingInitializer, false);

  for (auto *VD : SEAI->getStructDecl()->getStoredProperties()) {
    if (SEAI->getField() == VD)
      break;

    auto expansionContext = TypeExpansionContext(*SEAI->getFunction());
    auto FieldType = SEAI->getOperand()->getType().getFieldType(VD, Module, expansionContext);
    BaseEltNo += getElementCountRec(expansionContext, Module, FieldType, false);
  }

  collectUses(SEAI, BaseEltNo);
}

/// Return the underlying accessed pointer value. This peeks through
/// begin_access patterns such as:
///
/// %mark = mark_uninitialized [rootself] %alloc : $*T
/// %access = begin_access [modify] [unknown] %mark : $*T
/// apply %f(%access) : $(@inout T) -> ()
static SILValue getAccessedPointer(SILValue Pointer) {
  if (auto *Access = dyn_cast<BeginAccessInst>(Pointer))
    return Access->getSource();

  return Pointer;
}

static DIUseKind verifyCompilerInitialized(SILValue pointer,
                                           SILInstruction *write,
                                           DIUseKind origKind) {
  // if the write is _not_ auto-generated, it's a bad store.
  if (!write->getLoc().isAutoGenerated())
    return DIUseKind::BadExplicitStore;

  return origKind;
}

void ElementUseCollector::collectUses(SILValue Pointer, unsigned BaseEltNo) {
  assert(Pointer->getType().isAddress() &&
         "Walked through the pointer to the value?");
  SILType PointeeType = Pointer->getType().getObjectType();

  for (auto *Op : Pointer->getUses()) {
    auto *User = Op->getUser();

    // struct_element_addr P, #field indexes into the current element.
    if (auto *SEAI = dyn_cast<StructElementAddrInst>(User)) {
      collectStructElementUses(SEAI, BaseEltNo);
      continue;
    }

    // Instructions that compute a subelement are handled by a helper.
    if (auto *TEAI = dyn_cast<TupleElementAddrInst>(User)) {
      collectTupleElementUses(TEAI, BaseEltNo);
      continue;
    }

    // Look through begin_access.
    if (isa<BeginAccessInst>(User)) {
      auto begin = cast<SingleValueInstruction>(User);
      collectUses(begin, BaseEltNo);
      continue;
    }

    // Ignore end_access.
    if (isa<EndAccessInst>(User)) {
      continue;
    }

    // Look through mark_unresolved_non_copyable_value. To us, it is not
    // interesting.
    if (auto *mmi = dyn_cast<MarkUnresolvedNonCopyableValueInst>(User)) {
      collectUses(mmi, BaseEltNo);
      continue;
    }

    // Loads are a use of the value.
    if (isa<LoadInst>(User)) {
      addElementUses(BaseEltNo, PointeeType, User, DIUseKind::Load);
      continue;
    }

    // Load borrows are similar to loads except that we do not support
    // scalarizing them now.
    if (isa<LoadBorrowInst>(User)) {
      addElementUses(BaseEltNo, PointeeType, User, DIUseKind::Load);
      continue;
    }

#define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
    if (isa<Load##Name##Inst>(User)) { \
      trackUse(DIMemoryUse(User, DIUseKind::Load, BaseEltNo, 1)); \
      continue; \
    }
#include "swift/AST/ReferenceStorage.def"

    // Stores *to* the allocation are writes.
    if ((isa<StoreInst>(User) || isa<AssignInst>(User) ||
         isa<AssignByWrapperInst>(User)) &&
        Op->getOperandNumber() == 1) {
      // Coming out of SILGen, we assume that raw stores are initializations,
      // unless they have trivial type (which we classify as InitOrAssign).
      DIUseKind Kind;
      if (InStructSubElement)
        Kind = DIUseKind::PartialStore;
      else if (isa<AssignInst>(User) || isa<AssignByWrapperInst>(User))
        Kind = DIUseKind::InitOrAssign;
      else if (PointeeType.isTrivial(*User->getFunction()))
        Kind = DIUseKind::InitOrAssign;
      else
        Kind = DIUseKind::Initialization;

      // If it's a non-synthesized write to a @_compilerInitialized field,
      // indicate that in the Kind.
      if (LLVM_UNLIKELY(InCompilerInitializedField))
        Kind = verifyCompilerInitialized(Pointer, User, Kind);

      addElementUses(BaseEltNo, PointeeType, User, Kind);
      continue;
    }

#define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
    if (auto SWI = dyn_cast<Store##Name##Inst>(User)) \
      if (Op->getOperandNumber() == 1) { \
        DIUseKind Kind; \
        if (InStructSubElement) \
          Kind = DIUseKind::PartialStore; \
        else if (SWI->isInitializationOfDest()) \
          Kind = DIUseKind::Initialization; \
        else \
          Kind = DIUseKind::InitOrAssign; \
        trackUse(DIMemoryUse(User, Kind, BaseEltNo, 1)); \
        continue; \
      }
#include "swift/AST/ReferenceStorage.def"

    if (auto *CAI = dyn_cast<CopyAddrInst>(User)) {
      // If this is the source of the copy_addr, then this is a load.  If it is
      // the destination, then this is an unknown assignment.  Note that we'll
      // revisit this instruction and add it to Uses twice if it is both a load
      // and store to the same aggregate.
      DIUseKind Kind;
      if (Op->getOperandNumber() == 0)
        Kind = DIUseKind::Load;
      else if (InStructSubElement)
        Kind = DIUseKind::PartialStore;
      else if (CAI->isInitializationOfDest())
        Kind = DIUseKind::Initialization;
      else
        Kind = DIUseKind::InitOrAssign;

      addElementUses(BaseEltNo, PointeeType, User, Kind);
      continue;
    }

    if (auto *TACI = dyn_cast<TupleAddrConstructorInst>(User)) {
      // If this is the source of the copy_addr, then this is a load.  If it is
      // the destination, then this is an unknown assignment.  Note that we'll
      // revisit this instruction and add it to Uses twice if it is both a load
      // and store to the same aggregate.
      DIUseKind Kind;
      if (TACI->getDest() == Op->get()) {
        if (InStructSubElement)
          Kind = DIUseKind::PartialStore;
        else if (TACI->isInitializationOfDest())
          Kind = DIUseKind::Initialization;
        else
          Kind = DIUseKind::InitOrAssign;
      } else {
        Kind = DIUseKind::Load;
      }

      addElementUses(BaseEltNo, PointeeType, User, Kind);
      continue;
    }

    if (auto *MAI = dyn_cast<MarkUnresolvedMoveAddrInst>(User)) {
      // If this is the source of the copy_addr, then this is a load.  If it is
      // the destination, then this is an unknown assignment.  Note that we'll
      // revisit this instruction and add it to Uses twice if it is both a load
      // and store to the same aggregate.
      DIUseKind Kind;
      if (Op->getOperandNumber() == 0)
        Kind = DIUseKind::Load;
      else if (InStructSubElement)
        Kind = DIUseKind::PartialStore;
      else
        Kind = DIUseKind::Initialization;

      addElementUses(BaseEltNo, PointeeType, User, Kind);
      continue;
    }

    // The apply instruction does not capture the pointer when it is passed
    // through 'inout' arguments or for indirect returns.  InOut arguments are
    // treated as uses and may-store's, but an indirect return is treated as a
    // full store.
    //
    // Note that partial_apply instructions always close over their argument.
    //
    auto Apply = FullApplySite::isa(User);
    if (Apply) {
      auto substConv = Apply.getSubstCalleeConv();
      unsigned ArgumentNumber = Op->getOperandNumber() - 1;

      // If this is an out-parameter, it is like a store.
      unsigned NumIndirectResults = substConv.getNumIndirectSILResults() +
                                    substConv.getNumIndirectSILErrorResults();
      if (ArgumentNumber < NumIndirectResults) {
        assert(!InStructSubElement && "We're initializing sub-members?");
        addElementUses(BaseEltNo, PointeeType, User, DIUseKind::Initialization);
        continue;

        // Otherwise, adjust the argument index.
      } else {
        ArgumentNumber -= NumIndirectResults;
      }

      auto ParamConvention =
          substConv.getParameters()[ArgumentNumber].getConvention();

      switch (ParamConvention) {
      case ParameterConvention::Direct_Owned:
      case ParameterConvention::Direct_Unowned:
      case ParameterConvention::Direct_Guaranteed:
      case ParameterConvention::Pack_Guaranteed:
      case ParameterConvention::Pack_Owned:
      case ParameterConvention::Pack_Inout:
        llvm_unreachable("address value passed to indirect parameter");

      // If this is an in-parameter, it is like a load.
      case ParameterConvention::Indirect_In:
      case ParameterConvention::Indirect_In_Guaranteed:
        addElementUses(BaseEltNo, PointeeType, User, DIUseKind::IndirectIn);
        continue;

      
      // If this is an @inout parameter, it is like both a load and store.
      case ParameterConvention::Indirect_InoutAliasable: {
        // FIXME: The @inout_aliasable convention is used for indirect captures
        // of both 'let' and 'var' variables. Using a more specific convention
        // for 'let' properties like @in_guaranteed unfortunately exposes bugs
        // elsewhere in the pipeline. A 'let' capture cannot really be mutated
        // by the callee, and this is enforced by sema, so we can consider it
        // a nonmutating use.
        bool isLet = true;

        for (unsigned i = 0; i < TheMemory.getNumElements(); ++i) {
          if (!TheMemory.isElementLetProperty(i)) {
            isLet = false;
            break;
          }
        }

        if (isLet) {
          addElementUses(BaseEltNo, PointeeType, User, DIUseKind::IndirectIn);
          continue;
        }
        
        LLVM_FALLTHROUGH;
      }
      case ParameterConvention::Indirect_Inout: {
        // If we're in the initializer for a struct, and this is a call to a
        // mutating method, we model that as an escape of self.  If an
        // individual sub-member is passed as inout, then we model that as an
        // inout use.
        DIUseKind Kind;
        if (TheMemory.isStructInitSelf() &&
            getAccessedPointer(Pointer) == TheMemory.getUninitializedValue()) {
          Kind = DIUseKind::Escape;
        } else if (Apply.hasSelfArgument() &&
                   Op == &Apply.getSelfArgumentOperand()) {
          Kind = DIUseKind::InOutSelfArgument;
        } else {
          Kind = DIUseKind::InOutArgument;
        }

        addElementUses(BaseEltNo, PointeeType, User, Kind);
        continue;
      }
      }
      llvm_unreachable("bad parameter convention");
    }

    if (isa<AddressToPointerInst>(User)) {
      // address_to_pointer is a mutable escape, which we model as an inout use.
      addElementUses(BaseEltNo, PointeeType, User,
                     DIUseKind::InOutArgument);
      continue;
    }

    // init_enum_data_addr is treated like a tuple_element_addr or other
    // instruction
    // that is looking into the memory object (i.e., the memory object needs to
    // be explicitly initialized by a copy_addr or some other use of the
    // projected address).
    if (auto init = dyn_cast<InitEnumDataAddrInst>(User)) {
      assert(!InStructSubElement &&
             "init_enum_data_addr shouldn't apply to struct subelements");
      // Keep track of the fact that we're inside of an enum.  This informs our
      // recursion that tuple stores are not scalarized outside, and that stores
      // should not be treated as partial stores.
      llvm::SaveAndRestore<bool> X(InEnumSubElement, true);
      collectUses(init, BaseEltNo);
      continue;
    }

    // init_existential_addr is modeled as an initialization store.
    if (isa<InitExistentialAddrInst>(User)) {
      assert(!InStructSubElement &&
             "init_existential_addr should not apply to struct subelements");
      trackUse(DIMemoryUse(User, DIUseKind::Initialization, BaseEltNo, 1));
      continue;
    }

    // inject_enum_addr is modeled as an initialization store.
    if (isa<InjectEnumAddrInst>(User)) {
      assert(!InStructSubElement &&
             "inject_enum_addr the subelement of a struct unless in a ctor");
      trackUse(DIMemoryUse(User, DIUseKind::Initialization, BaseEltNo, 1));
      continue;
    }

    // open_existential_addr is either a load or a modification depending on
    // how it's marked.  Note that the difference is just about immutability
    // checking rather than checking initialization before use.
    if (auto open = dyn_cast<OpenExistentialAddrInst>(User)) {
      // TODO: Is it reasonable to just honor the marking, or should we look
      // at all the uses of the open_existential_addr in case one they're
      // all really just loads?
      switch (open->getAccessKind()) {
      case OpenedExistentialAccess::Immutable:
        trackUse(DIMemoryUse(User, DIUseKind::Load, BaseEltNo, 1));
        continue;

      case OpenedExistentialAccess::Mutable:
        trackUse(DIMemoryUse(User, DIUseKind::InOutArgument, BaseEltNo, 1));
        continue;
      }
      llvm_unreachable("bad access kind");
    }

    // unchecked_take_enum_data_addr takes the address of the payload of an
    // optional, which could be used to update the payload. So, visit the
    // users of this instruction and ensure that there are no overwrites to an
    // immutable optional. Note that this special handling is for checking
    // immutability and is not for checking initialization before use.
    if (auto *enumDataAddr = dyn_cast<UncheckedTakeEnumDataAddrInst>(User)) {
      // Keep track of the fact that we're inside of an enum. This informs our
      // recursion that tuple stores should not be treated as a partial
      // store. This is needed because if the enum has data it would be accessed
      // through tuple_element_addr instruction. The entire enum is expected
      // to be initialized before any such access.
      llvm::SaveAndRestore<bool> X(InEnumSubElement, true);
      collectUses(enumDataAddr, BaseEltNo);
      continue;
    }

    // 'select_enum_addr' selects one of the two operands based on the case
    // of an enum value.
    // 'switch_enum_addr' jumps to one of the two branch labels (provided as
    // operands) based on the case of the enum value.
    if (isa<SelectEnumAddrInst>(User) || isa<SwitchEnumAddrInst>(User)) {
      trackUse(DIMemoryUse(User, DIUseKind::Load, BaseEltNo, 1));
      continue;
    }

    // We model destroy_addr as a release of the entire value.
    if (isa<DestroyAddrInst>(User)) {
      trackDestroy(User);
      continue;
    }

    if (isa<DeallocStackInst>(User)) {
      continue;
    }

    if (User->isDebugInstruction())
      continue;

    if (auto *AI = dyn_cast<AssignOrInitInst>(User)) {
      collectAssignOrInitUses(AI, BaseEltNo);
      continue;
    }

    if (auto *PAI = dyn_cast<PartialApplyInst>(User)) {
      if (onlyUsedByAssignByWrapper(PAI))
        continue;

      if (onlyUsedByAssignOrInit(PAI))
        continue;

      if (BaseEltNo == 0 && addClosureElementUses(PAI, Op))
        continue;
    }

    // Sanitizer instrumentation is not user visible, so it should not
    // count as a use and must not affect compile-time diagnostics.
    if (isSanitizerInstrumentation(User))
      continue;

    // Otherwise, the use is something complicated, it escapes.
    addElementUses(BaseEltNo, PointeeType, User, DIUseKind::Escape);
  }
}

/// Add all used elements of an implicit closure, which is capturing 'self'.
///
/// We want to correctly handle implicit closures in initializers, e.g. with
/// boolean operators:
/// \code
///   init() {
///     bool_member1 = false
///     bool_member2 = false || bool_member1 // implicit closure
///   }
/// \endcode
///
/// The implicit closure ('bool_member1' at the RHS of the || operator) captures
/// the whole self, but only uses 'bool_member1'.
/// If we would add the whole captured 'self' as use, we would get a
/// "'self.bool_member2' not initialized" error at the partial_apply.
/// Therefore we look into the body of the closure and only add the actually
/// used members.
bool ElementUseCollector::addClosureElementUses(PartialApplyInst *pai,
                                                Operand *argUse) {
  SILFunction *callee = pai->getReferencedFunctionOrNull();
  if (!callee)
    return false;

  // Implicit closures are "transparent", which means they are always inlined.
  // It would probably also work to handle non-transparent closures (e.g.
  // explicit closures). But if the closure is not inlined we could end up
  // passing a partially initialized self to the closure function. Although it
  // would probably not cause any real problems, an `@in_guaranteed` argument
  // (the captured 'self') is assumed to be fully initialized in SIL.
  if (!callee->isTransparent())
    return false;

  // Implicit closures are only partial-applied once and there cannot be a
  // recursive cycle of implicit closures.
  // Nevertheless such a scenario is theoretically possible in SIL. To be on the
  // safe side, check for cycles.
  if (!VisitedClosures.insert(callee).second)
    return false;

  unsigned argIndex = ApplySite(pai).getCalleeArgIndex(*argUse);
  SILArgument *arg = callee->getArgument(argIndex);
  
  // Bail if arg is not the original 'self' object, but e.g. a projected member.
  assert(TheMemory.getType().isObject());
  if (arg->getType().getObjectType() != TheMemory.getType())
    return false;

  DIElementUseInfo ArgUseInfo;
  ElementUseCollector collector(TheMemory, ArgUseInfo, VisitedClosures);
  collector.collectFrom(arg, /*collectDestroysOfContainer*/ false);

  if (!ArgUseInfo.Releases.empty() || !ArgUseInfo.StoresToSelf.empty())
    return false;
    
  for (const DIMemoryUse &use : ArgUseInfo.Uses) {
    // Only handle loads and escapes. Implicit closures will not have stores or
    // store-like uses, anyway.
    // Also, as we don't do a flow-sensitive analysis of the callee, we cannot
    // handle stores, because we don't know if they are unconditional or not.
    switch (use.Kind) {
      case DIUseKind::Load:
      case DIUseKind::Escape:
      case DIUseKind::InOutArgument:
        break;
      default:
        return false;
    }
  }

  // Track all uses of the closure.
  for (const DIMemoryUse &use : ArgUseInfo.Uses) {
    trackUse(DIMemoryUse(pai, use.Kind, use.FirstElement, use.NumElements));
  }
  return true;
}

void
ElementUseCollector::collectAssignOrInitUses(AssignOrInitInst *Inst,
                                             unsigned BaseEltNo) {
  /// AssignOrInit doesn't operate on `self` so we need to make sure
  /// that the flag is dropped before calling \c addElementUses.
  llvm::SaveAndRestore<bool> X(IsSelfOfNonDelegatingInitializer, false);

  auto *typeDC = Inst->getReferencedInitAccessor()
                     ->getDeclContext()
                     ->getSelfNominalTypeDecl();

  auto expansionContext = TypeExpansionContext(TheMemory.getFunction());

  auto selfTy = Inst->getSelf()->getType();

  auto addUse = [&](VarDecl *property, DIUseKind useKind) {
    unsigned fieldIdx = 0;
    for (auto *VD : typeDC->getStoredProperties()) {
      if (VD == property)
        break;

      fieldIdx += getElementCountRec(
          expansionContext, Module,
          selfTy.getFieldType(VD, Module, expansionContext), false);
    }

    auto type = selfTy.getFieldType(property, Module, expansionContext);
    addElementUses(fieldIdx, type, Inst, useKind, property);
  };

  auto initializedElts = Inst->getInitializedProperties();
  if (initializedElts.empty()) {
    auto initAccessorProperties = typeDC->getInitAccessorProperties();
    auto initFieldAt = typeDC->getStoredProperties().size();

    for (auto *property : initAccessorProperties) {
      auto initAccessor = property->getAccessor(AccessorKind::Init);
      if (!initAccessor->getInitializedProperties().empty())
        continue;

      if (property == Inst->getProperty()) {
        trackUse(DIMemoryUse(Inst, DIUseKind::InitOrAssign, initFieldAt,
                             /*NumElements=*/1));
        break;
      }

      ++initFieldAt;
    }
  } else {
    for (auto *property : initializedElts)
      addUse(property, DIUseKind::InitOrAssign);
  }

  for (auto *property : Inst->getAccessedProperties())
    addUse(property, DIUseKind::Load);
}

/// collectClassSelfUses - Collect all the uses of a 'self' pointer in a class
/// constructor.  The memory object has class type.
void ElementUseCollector::collectClassSelfUses(SILValue ClassPointer) {
  assert(IsSelfOfNonDelegatingInitializer &&
         TheMemory.getASTType()->getClassOrBoundGenericClass() != nullptr);

  // For efficiency of lookup below, compute a mapping of the local ivars in the
  // class to their element number.
  llvm::SmallDenseMap<VarDecl *, unsigned> EltNumbering;

  {
    SILType T = TheMemory.getType();
    auto *NTD = T.getNominalOrBoundGenericNominal();
    unsigned NumElements = 0;
    for (auto *VD : NTD->getStoredProperties()) {
      EltNumbering[VD] = NumElements;
      auto expansionContext = TypeExpansionContext(TheMemory.getFunction());
      NumElements += getElementCountRec(
          expansionContext, Module,
          T.getFieldType(VD, Module, expansionContext), false);
    }
  }

  // If we are looking at the init method for a root class, just walk the
  // MUI use-def chain directly to find our uses.
  if (TheMemory.isRootSelf() ||
  
      // Also, just visit all users if ClassPointer is a closure argument,
      // i.e. collectClassSelfUses is called from addClosureElementUses.
      isa<SILFunctionArgument>(ClassPointer)) {
    collectClassSelfUses(ClassPointer, TheMemory.getType(), EltNumbering);
    return;
  }

  // The number of stores of the initial 'self' argument into the self box
  // that we saw.
  unsigned StoresOfArgumentToSelf = 0;

  // Okay, given that we have a proper setup, we walk the use chains of the self
  // box to find any accesses to it. The possible uses are one of:
  //
  //   1) The initialization store.
  //   2) Loads of the box, which have uses of self hanging off of them.
  //   3) An assign to the box, which happens at super.init.
  //   4) Potential escapes after super.init, if self is closed over.
  //
  // Handle each of these in turn.
  SmallVector<Operand *, 8> Uses(TheMemory.getUninitializedValue()->getUses());
  while (!Uses.empty()) {
    Operand *Op = Uses.pop_back_val();
    SILInstruction *User = Op->getUser();

    // Stores to self.
    if (auto *SI = dyn_cast<StoreInst>(User)) {
      if (Op->getOperandNumber() == 1) {
        // The initial store of 'self' into the box at the start of the
        // function. Ignore it.
        if (auto *Arg = dyn_cast<SILArgument>(SI->getSrc())) {
          if (Arg->getParent() == TheMemory.getParentBlock()) {
            ++StoresOfArgumentToSelf;
            continue;
          }
        }

        // A store of a load from the box is ignored.
        // SILGen emits these if delegation to another initializer was
        // interrupted before the initializer was called.
        SILValue src = SI->getSrc();
        // Look through conversions.
        while (auto conversion = ConversionOperation(src))
          src = conversion.getConverted();

        if (auto *LI = dyn_cast<LoadInst>(src))
          if (LI->getOperand() == TheMemory.getUninitializedValue())
            continue;

        // Any other store needs to be recorded.
        UseInfo.trackStoreToSelf(SI);
        continue;
      }
    }

    // Ignore end_borrows. These can only come from us being the source of a
    // load_borrow.
    if (isa<EndBorrowInst>(User))
      continue;

    // Recurse through begin_access.
    if (auto *beginAccess = dyn_cast<BeginAccessInst>(User)) {
      Uses.append(beginAccess->getUses().begin(), beginAccess->getUses().end());
      continue;
    }

    if (isa<EndAccessInst>(User))
      continue;

    // Loads of the box produce self, so collect uses from them.
    if (isa<LoadInst>(User) || isa<LoadBorrowInst>(User)) {
      auto load = cast<SingleValueInstruction>(User);
      collectClassSelfUses(load, TheMemory.getType(), EltNumbering);
      continue;
    }

    // destroy_addr on the box is load+release, which is treated as a release.
    if (isa<DestroyAddrInst>(User) || isa<StrongReleaseInst>(User) ||
        isa<DestroyValueInst>(User)) {
      trackDestroy(User);
      continue;
    }

    // Ignore the deallocation of the stack box.  Its contents will be
    // uninitialized by the point it executes.
    if (isa<DeallocStackInst>(User))
      continue;

    // We can safely handle anything else as an escape.  They should all happen
    // after super.init is invoked.  As such, all elements must be initialized
    // and super.init must be called.
    trackUse(DIMemoryUse(User, DIUseKind::Load, 0, TheMemory.getNumElements()));
  }

  assert(StoresOfArgumentToSelf == 1 &&
         "The 'self' argument should have been stored into the box exactly once");
}

static bool isSuperInitUse(SILInstruction *User) {
  auto *LocExpr = User->getLoc().getAsASTNode<ApplyExpr>();
  if (!LocExpr) {
    // If we're reading a .sil file, treat a call to "superinit" as a
    // super.init call as a hack to allow us to write testcases.
    auto *AI = dyn_cast<ApplyInst>(User);
    if (AI && AI->getLoc().isSILFile())
      if (auto *Fn = AI->getReferencedFunctionOrNull())
        if (Fn->getName() == "superinit")
          return true;
    return false;
  }

  // This is a super.init call if structured like this:
  // (call_expr type='SomeClass'
  //   (dot_syntax_call_expr type='() -> SomeClass' super
  //     (other_constructor_ref_expr implicit decl=SomeClass.init)
  //     (super_ref_expr type='SomeClass'))
  //   (...some argument...)
  LocExpr = dyn_cast<ApplyExpr>(LocExpr->getFn());
  if (!LocExpr || !isa<OtherConstructorDeclRefExpr>(LocExpr->getFn()))
    return false;

  auto *UnaryArg = LocExpr->getArgs()->getUnaryExpr();
  assert(UnaryArg);
  if (UnaryArg->isSuperExpr())
    return true;

  // Instead of super_ref_expr, we can also get this for inherited delegating
  // initializers:

  // (derived_to_base_expr implicit type='C'
  //   (declref_expr type='D' decl='self'))
  if (auto *DTB = dyn_cast<DerivedToBaseExpr>(UnaryArg)) {
    if (auto *DRE = dyn_cast<DeclRefExpr>(DTB->getSubExpr())) {
        ASTContext &Ctx = DRE->getDecl()->getASTContext();
      if (DRE->getDecl()->isImplicit() &&
          DRE->getDecl()->getBaseName() == Ctx.Id_self)
        return true;
    }
  }

  return false;
}

/// Return true if this SILBBArgument is the result of a call to super.init.
static bool isSuperInitUse(SILArgument *Arg) {
  // We only handle a very simple pattern here where there is a single
  // predecessor to the block, and the predecessor instruction is a try_apply
  // of a throwing delegated init.
  auto *BB = Arg->getParent();
  auto *Pred = BB->getSinglePredecessorBlock();

  // The two interesting cases are where self.init throws, in which case
  // the argument came from a try_apply, or if self.init is failable,
  // in which case we have a switch_enum.
  if (!Pred || (!isa<TryApplyInst>(Pred->getTerminator()) &&
                !isa<SwitchEnumInst>(Pred->getTerminator())))
    return false;

  return isSuperInitUse(Pred->getTerminator());
}

static bool isUninitializedMetatypeInst(SILInstruction *I) {
  // A simple reference to "type(of:)" is always fine,
  // even if self is uninitialized.
  if (isa<ValueMetatypeInst>(I))
    return true;

  // Sometimes we get an upcast whose sole usage is a value_metatype_inst,
  // for example when calling a convenience initializer from a superclass.
  if (auto *UCI = dyn_cast<UpcastInst>(I)) {
    for (auto *Op : UCI->getUses()) {
      auto *User = Op->getUser();
      if (isa<ValueMetatypeInst>(User))
        continue;
      return false;
    }

    return true;
  }

  return false;
}

/// isSelfInitUse - Return true if this apply_inst is a call to self.init.
static bool isSelfInitUse(SILInstruction *I) {
  // If we're reading a .sil file, treat a call to "selfinit" as a
  // self.init call as a hack to allow us to write testcases.
  if (I->getLoc().isSILFile()) {
    if (auto *AI = dyn_cast<ApplyInst>(I))
      if (auto *Fn = AI->getReferencedFunctionOrNull())
        if (Fn->getName().starts_with("selfinit"))
          return true;

    return false;
  }

  // Otherwise, a self.init call must have location info, and must be an expr
  // to be considered.
  auto *LocExpr = I->getLoc().getAsASTNode<Expr>();
  if (!LocExpr)
    return false;

  // If this is a force_value_expr, it might be a self.init()! call, look
  // through it.
  if (auto *FVE = dyn_cast<ForceValueExpr>(LocExpr))
    LocExpr = FVE->getSubExpr();

  // If we have the rebind_self_in_constructor_expr, then the call is the
  // sub-expression.
  if (auto *RB = dyn_cast<RebindSelfInConstructorExpr>(LocExpr)) {
    LocExpr = RB->getSubExpr();
    // Look through TryExpr or ForceValueExpr, but not both.
    if (auto *TE = dyn_cast<AnyTryExpr>(LocExpr))
      LocExpr = TE->getSubExpr();
    else if (auto *FVE = dyn_cast<ForceValueExpr>(LocExpr))
      LocExpr = FVE->getSubExpr();
  }

  // Look through covariant return, if any.
  if (auto CRE = dyn_cast<CovariantReturnConversionExpr>(LocExpr))
    LocExpr = CRE->getSubExpr();

  // This is a self.init call if structured like this:
  //
  // (call_expr type='SomeClass'
  //   (dot_syntax_call_expr type='() -> SomeClass' self
  //     (other_constructor_ref_expr implicit decl=SomeClass.init)
  //     (decl_ref_expr type='SomeClass', "self"))
  //   (...some argument...)
  //
  // Or like this:
  //
  // (call_expr type='SomeClass'
  //   (dot_syntax_call_expr type='() -> SomeClass' self
  //     (decr_ref_expr implicit decl=SomeClass.init)
  //     (decl_ref_expr type='SomeClass', "self"))
  //   (...some argument...)
  //
  if (auto *AE = dyn_cast<ApplyExpr>(LocExpr)) {
    if ((AE = dyn_cast<ApplyExpr>(AE->getFn()))) {
      if (isa<OtherConstructorDeclRefExpr>(AE->getFn()))
        return true;
      if (auto *DRE = dyn_cast<DeclRefExpr>(AE->getFn()))
        if (auto *CD = dyn_cast<ConstructorDecl>(DRE->getDecl()))
          if (CD->isFactoryInit())
            return true;
    }
  }
  return false;
}

/// Return true if this SILBBArgument is the result of a call to self.init.
static bool isSelfInitUse(SILArgument *Arg) {
  // We only handle a very simple pattern here where there is a single
  // predecessor to the block, and the predecessor instruction is a try_apply
  // of a throwing delegated init.
  auto *BB = Arg->getParent();
  auto *Pred = BB->getSinglePredecessorBlock();

  // The two interesting cases are where self.init throws, in which case
  // the argument came from a try_apply, or if self.init is failable,
  // in which case we have a switch_enum.
  if (!Pred || (!isa<TryApplyInst>(Pred->getTerminator()) &&
                !isa<SwitchEnumInst>(Pred->getTerminator())))
    return false;

  return isSelfInitUse(Pred->getTerminator());
}

static bool isSelfOperand(const Operand *Op, const SILInstruction *User) {
  unsigned operandNum = Op->getOperandNumber();
  unsigned numOperands;

  // FIXME: This should just be cast<FullApplySite>(User) but that doesn't
  // work
  if (auto *AI = dyn_cast<ApplyInst>(User))
    numOperands = AI->getNumOperands();
  else
    numOperands = cast<TryApplyInst>(User)->getNumOperands();

  return (operandNum == numOperands - 1);
}

void ElementUseCollector::collectClassSelfUses(
    SILValue ClassPointer, SILType MemorySILType,
    llvm::SmallDenseMap<VarDecl *, unsigned> &EltNumbering) {
  llvm::SmallVector<Operand *, 16> Worklist(ClassPointer->use_begin(),
                                            ClassPointer->use_end());
  while (!Worklist.empty()) {
    auto *Op = Worklist.pop_back_val();
    auto *User = Op->getUser();

    // Ignore any method lookup use.
    if (isa<SuperMethodInst>(User) ||
        isa<ObjCSuperMethodInst>(User) ||
        isa<ClassMethodInst>(User) ||
        isa<ObjCMethodInst>(User)) {
      continue;
    }

    // Skip end_borrow and end_access.
    if (isa<EndBorrowInst>(User) || isa<EndAccessInst>(User))
      continue;

    // ref_element_addr P, #field lookups up a field.
    if (auto *REAI = dyn_cast<RefElementAddrInst>(User)) {
      // FIXME: This is a Sema bug and breaks resilience, we should not
      // emit ref_element_addr in such cases at all.
      if (EltNumbering.count(REAI->getField()) != 0) {
        assert(EltNumbering.count(REAI->getField()) &&
               "ref_element_addr not a local field?");

        // Remember whether the field is marked '@_compilerInitialized'
        const bool hasCompInit =
          REAI->getField()->getAttrs().hasAttribute<CompilerInitializedAttr>();
        llvm::SaveAndRestore<bool> X1(InCompilerInitializedField, hasCompInit);

        // Recursively collect uses of the fields.  Note that fields of the class
        // could be tuples, so they may be tracked as independent elements.
        llvm::SaveAndRestore<bool> X2(IsSelfOfNonDelegatingInitializer, false);
        collectUses(REAI, EltNumbering[REAI->getField()]);
        continue;
      }
    }

    // retains of self in class constructors can be ignored since we do not care
    // about the retain that we are producing, but rather the consumer of the
    // retain. This /should/ be true today and will be verified as true in
    // Semantic SIL.
    if (isa<StrongRetainInst>(User)) {
      continue;
    }

    // Destroys of self are tracked as a release.
    //
    // *NOTE* In the case of a failing initializer, the release on the exit path
    // needs to cleanup the partially initialized elements.
    if (isa<StrongReleaseInst>(User) || isa<DestroyValueInst>(User)) {
      trackDestroy(User);
      continue;
    }

    // Look through begin_borrow, upcast, unchecked_ref_cast
    // and copy_value.
    if (isa<BeginBorrowInst>(User) || isa<BeginAccessInst>(User) ||
        isa<UpcastInst>(User) || isa<UncheckedRefCastInst>(User) ||
        isa<CopyValueInst>(User) ||
        isa<MarkUnresolvedNonCopyableValueInst>(User)) {
      auto value = cast<SingleValueInstruction>(User);
      std::copy(value->use_begin(), value->use_end(),
                std::back_inserter(Worklist));
      continue;
    }

    // If this is an ApplyInst, check to see if this is part of a self.init
    // call in a delegating initializer.
    DIUseKind Kind = DIUseKind::Load;
    if (isa<FullApplySite>(User) &&
        (isSelfInitUse(User) || isSuperInitUse(User))) {
      if (isSelfOperand(Op, User)) {
        Kind = DIUseKind::SelfInit;
      }
    }
    
    if (isUninitializedMetatypeInst(User))
      continue;

    if (User->isDebugInstruction())
      continue;

    if (auto *AI = dyn_cast<AssignOrInitInst>(User)) {
      collectAssignOrInitUses(AI);
      continue;
    }

    // If this is a partial application of self, then this is an escape point
    // for it.
    if (auto *PAI = dyn_cast<PartialApplyInst>(User)) {
      if (onlyUsedByAssignByWrapper(PAI))
        continue;

      if (onlyUsedByAssignOrInit(PAI))
        continue;

      if (addClosureElementUses(PAI, Op))
        continue;

      Kind = DIUseKind::Escape;
    }

    // Track flow-sensitive 'self' isolation builtins separately, because they
    // aren't really uses of 'self' until after DI, once we've decided whether
    // they have a fully-formed 'self' to use.
    if (auto builtin = dyn_cast<BuiltinInst>(User)) {
      if (auto builtinKind = builtin->getBuiltinKind()) {
        if (*builtinKind == BuiltinValueKind::FlowSensitiveSelfIsolation ||
            *builtinKind ==
              BuiltinValueKind::FlowSensitiveDistributedSelfIsolation) {
          Kind = DIUseKind::FlowSensitiveSelfIsolation;
        }
      }
    }

    trackUse(DIMemoryUse(User, Kind, 0, TheMemory.getNumElements()));
  }
}

//===----------------------------------------------------------------------===//
//                         DelegatingInitUseCollector
//===----------------------------------------------------------------------===//

static void
collectDelegatingInitUses(const DIMemoryObjectInfo &TheMemory,
                          DIElementUseInfo &UseInfo,
                          SingleValueInstruction *I) {
  for (auto *Op : I->getUses()) {
    SILInstruction *User = Op->getUser();

    // destroy_addr is a release of the entire value. This can result from an
    // early release due to a conditional initializer.
    if (isa<DestroyAddrInst>(User)) {
      UseInfo.trackDestroy(User);
      continue;
    }

    // For delegating initializers, we only track calls to self.init with
    // specialized code. All other uses are modeled as escapes.
    //
    // *NOTE* This intentionally ignores all stores, which (if they got emitted
    // as copyaddr or assigns) will eventually get rewritten as assignments (not
    // initializations), which is the right thing to do.
    DIUseKind Kind = DIUseKind::Escape;

    // Stores *to* the allocation are writes.  If the value being stored is a
    // call to self.init()... then we have a self.init call.
    if (auto *AI = dyn_cast<AssignInst>(User)) {
      if (AI->getDest() == I) {
        UseInfo.trackStoreToSelf(AI);
        Kind = DIUseKind::InitOrAssign;
      }
    }

    if (auto *CAI = dyn_cast<CopyAddrInst>(User)) {
      if (CAI->getDest() == I) {
        UseInfo.trackStoreToSelf(CAI);
        Kind = DIUseKind::InitOrAssign;
      }
    }

    if (auto *MAI = dyn_cast<MarkUnresolvedMoveAddrInst>(User)) {
      if (MAI->getDest() == I) {
        UseInfo.trackStoreToSelf(MAI);
        Kind = DIUseKind::Initialization;
      }
    }

    // Look through begin_access
    if (auto *BAI = dyn_cast<BeginAccessInst>(User)) {
      collectDelegatingInitUses(TheMemory, UseInfo, BAI);
      continue;
    }

    // Look through mark_unresolved_non_copyable_value.
    if (auto *MMCI = dyn_cast<MarkUnresolvedNonCopyableValueInst>(User)) {
      collectDelegatingInitUses(TheMemory, UseInfo, MMCI);
      continue;
    }

    // Ignore end_access
    if (isa<EndAccessInst>(User))
      continue;
    
    // A load of the value that's only used to handle a type(of:) query before
    // self has been initialized can just use the initializer's metatype
    // argument. For value types, there's no metatype subtyping to worry about,
    // and for class convenience initializers, `self` notionally has the
    // original Self type as its dynamic type before theoretically being
    // rebound.
    //
    // This is necessary for source compatibility; previously, convenience
    // initializers behaved like in Objective-C where the initializer received
    // an uninitialized object to fill in, and type(of: self) worked by asking
    // for the dynamic type of that uninitialized object.
    if (isa<LoadInst>(User)) {
      auto UserVal = cast<SingleValueInstruction>(User);
      if (UserVal->hasOneUse()
          && isa<ValueMetatypeInst>(UserVal->getSingleUse()->get())) {
        Kind = DIUseKind::LoadForTypeOfSelf;
      }
    }
    // value_metatype may appear on a borrowed load, in which case there'll
    // be an end_borrow use in addition to the value_metatype.
    if (isa<LoadBorrowInst>(User)) {
      auto UserVal = cast<SingleValueInstruction>(User);
      bool onlyUseIsValueMetatype = false;
      for (auto use : UserVal->getUses()) {
        auto *user = use->getUser();
        if (isa<EndBorrowInst>(user))
          continue;
        if (isa<ValueMetatypeInst>(user)) {
          onlyUseIsValueMetatype = true;
          continue;
        }
        onlyUseIsValueMetatype = false;
        break;
      }
      if (onlyUseIsValueMetatype) {
        Kind = DIUseKind::LoadForTypeOfSelf;
      }
    }
    // value_metatype may also use the 'self' value directly, if it has an
    // address-only type.
    if (isa<ValueMetatypeInst>(User))
      Kind = DIUseKind::TypeOfSelf;

    // We can safely handle anything else as an escape.  They should all happen
    // after self.init is invoked.
    UseInfo.trackUse(DIMemoryUse(User, Kind, 0, 1));
  }
}

//===----------------------------------------------------------------------===//
//                        ClassInitElementUseCollector
//===----------------------------------------------------------------------===//

namespace {

class ClassInitElementUseCollector {
  const DIMemoryObjectInfo &TheMemory;
  DIElementUseInfo &UseInfo;

public:
  ClassInitElementUseCollector(const DIMemoryObjectInfo &TheMemory,
                                         DIElementUseInfo &UseInfo)
      : TheMemory(TheMemory), UseInfo(UseInfo) {}

  void collectClassInitSelfUses();

  // *NOTE* Even though this takes a SILInstruction it actually only accepts
  // load_borrow and load instructions. This is enforced via an assert.
  void collectClassInitSelfLoadUses(SingleValueInstruction *MUI,
                                    SingleValueInstruction *LI);
};

} // end anonymous namespace

/// collectDelegatingClassInitSelfUses - Collect uses of the self argument in a
/// delegating-constructor-for-a-class case.
void ClassInitElementUseCollector::collectClassInitSelfUses() {
  // When we're analyzing a delegating constructor, we aren't field sensitive at
  // all.  Just treat all members of self as uses of the single
  // non-field-sensitive value.
  assert(TheMemory.getNumElements() == 1 && "delegating inits only have 1 bit");
  auto *uninitMemory = TheMemory.getUninitializedValue();

  // The number of stores of the initial 'self' argument into the self box
  // that we saw.
  unsigned StoresOfArgumentToSelf = 0;

  // We walk the use chains of the self uninitMemory to find any accesses to it.
  // The possible uses are:
  //   1) The initialization store.
  //   2) Loads of the box, which have uses of self hanging off of them.
  //   3) An assign to the box, which happens at super.init.
  //   4) Potential escapes after super.init, if self is closed over.
  // Handle each of these in turn.
  //
  SmallVector<Operand *, 8> Uses(uninitMemory->getUses());
  while (!Uses.empty()) {
    Operand *Op = Uses.pop_back_val();
    SILInstruction *User = Op->getUser();

    // Ignore end_borrow. If we see an end_borrow it can only come from a
    // load_borrow from ourselves.
    if (isa<EndBorrowInst>(User))
      continue;

    // Recurse through begin_access.
    if (auto *beginAccess = dyn_cast<BeginAccessInst>(User)) {
      Uses.append(beginAccess->getUses().begin(), beginAccess->getUses().end());
      continue;
    }
    if (isa<EndAccessInst>(User))
      continue;

    // Stores to self.
    if (auto *SI = dyn_cast<StoreInst>(User)) {
      if (Op->getOperandNumber() == 1) {
        // A store of 'self' into the box at the start of the
        // function. Ignore it.
        if (auto *Arg = dyn_cast<SILArgument>(SI->getSrc())) {
          if (Arg->getParent() == uninitMemory->getParent()) {
            ++StoresOfArgumentToSelf;
            continue;
          }
        }

        // A store of a load from the box is ignored.
        //
        // SILGen emits these if delegation to another initializer was
        // interrupted before the initializer was called.
        SILValue src = SI->getSrc();
        // Look through conversions.
        while (auto conversion = ConversionOperation(src))
          src = conversion.getConverted();

        if (auto *LI = dyn_cast<LoadInst>(src))
          if (LI->getOperand() == uninitMemory)
            continue;

        // Any other store needs to be recorded.
        UseInfo.trackStoreToSelf(SI);
        continue;
      }
    }

    // For class initializers, the assign into the self box may be
    // captured as SelfInit or SuperInit elsewhere.
    if (isa<AssignInst>(User) &&
        Op->getOperandNumber() == 1) {
      // If the source of the assignment is an application of a C
      // function, there is no metatype argument, so treat the
      // assignment to the self box as the initialization.
      if (auto *AI = dyn_cast<ApplyInst>(cast<AssignInst>(User)->getSrc())) {
        if (auto *Fn = AI->getCalleeFunction()) {
          if (Fn->getRepresentation() ==
              SILFunctionTypeRepresentation::CFunctionPointer) {
            UseInfo.trackStoreToSelf(User);
            UseInfo.trackUse(DIMemoryUse(User, DIUseKind::SelfInit, 0, 1));
            continue;
          }
        }
      }
    }

    // Stores *to* the allocation are writes.  If the value being stored is a
    // call to self.init()... then we have a self.init call.
    if (auto *AI = dyn_cast<AssignInst>(User)) {
      if (auto *AssignSource = AI->getOperand(0)->getDefiningInstruction()) {
        if (isSelfInitUse(AssignSource) || isSuperInitUse(AssignSource)) {
          UseInfo.trackStoreToSelf(User);
          UseInfo.trackUse(DIMemoryUse(User, DIUseKind::SelfInit, 0, 1));
          continue;
        }
      }
      if (auto *AssignSource = dyn_cast<SILArgument>(AI->getOperand(0))) {
        if (AssignSource->getParent() == AI->getParent() &&
            (isSelfInitUse(AssignSource) || isSuperInitUse(AssignSource))) {
          UseInfo.trackStoreToSelf(User);
          UseInfo.trackUse(DIMemoryUse(User, DIUseKind::SelfInit, 0, 1));
          continue;
        }
      }
    }

    // Loads of the box produce self, so collect uses from them.
    if (isa<LoadInst>(User) || isa<LoadBorrowInst>(User)) {
      collectClassInitSelfLoadUses(uninitMemory,
                                   cast<SingleValueInstruction>(User));
      continue;
    }

    // destroy_addr on the box is load+release, which is treated as a release.
    if (isa<DestroyAddrInst>(User)) {
      UseInfo.trackDestroy(User);
      continue;
    }

    // We can safely handle anything else as an escape.  They should all happen
    // after self.init is invoked.
    UseInfo.trackUse(DIMemoryUse(User, DIUseKind::Escape, 0, 1));
  }

  assert(StoresOfArgumentToSelf == 1 &&
         "The 'self' argument should have been stored into the box exactly once");
}

void ClassInitElementUseCollector::collectClassInitSelfLoadUses(
    SingleValueInstruction *MUI, SingleValueInstruction *LI) {
  assert(isa<ProjectBoxInst>(MUI) || isa<MarkUninitializedInst>(MUI));
  assert(isa<LoadBorrowInst>(LI) || isa<LoadInst>(LI));

  // If we have a load, then this is a use of the box.  Look at the uses of
  // the load to find out more information.
  llvm::SmallVector<Operand *, 8> Worklist(LI->use_begin(), LI->use_end());
  while (!Worklist.empty()) {
    auto *Op = Worklist.pop_back_val();
    auto *User = Op->getUser();

    // Ignore any method lookup use.
    if (isa<SuperMethodInst>(User) ||
        isa<ObjCSuperMethodInst>(User) ||
        isa<ClassMethodInst>(User) ||
        isa<ObjCMethodInst>(User)) {
      continue;
    }

    // We ignore retains of self.
    if (isa<StrongRetainInst>(User))
      continue;

    // Ignore end_borrow.
    if (isa<EndBorrowInst>(User))
      continue;

    // A release of a load from the self box in a class delegating
    // initializer might be releasing an uninitialized self, which requires
    // special processing.
    if (isa<StrongReleaseInst>(User) || isa<DestroyValueInst>(User)) {
      UseInfo.trackDestroy(User);
      continue;
    }

    // Look through begin_borrow, upcast and unchecked_ref_cast.
    if (isa<BeginBorrowInst>(User) ||
        isa<UpcastInst>(User) ||
        isa<UncheckedRefCastInst>(User)) {
      auto I = cast<SingleValueInstruction>(User);
      llvm::copy(I->getUses(), std::back_inserter(Worklist));
      continue;
    }

    // We only track two kinds of uses for delegating initializers:
    // calls to self.init, and "other", which we choose to model as escapes.
    // This intentionally ignores all stores, which (if they got emitted as
    // copyaddr or assigns) will eventually get rewritten as assignments
    // (not initializations), which is the right thing to do.
    DIUseKind Kind = DIUseKind::Escape;

    // If this is an ApplyInst, check to see if this is part of a self.init
    // call in a delegating initializer.
    if (isa<FullApplySite>(User) &&
        (isSelfInitUse(User) || isSuperInitUse(User))) {
      if (isSelfOperand(Op, User)) {
        Kind = DIUseKind::SelfInit;
      }
    }

    // If this load's value is being stored immediately back into the delegating
    // mark_uninitialized buffer, skip the use.
    //
    // This is to handle situations where we do not actually consume self as a
    // result of situations such as:
    //
    // 1. The usage of a metatype to allocate the object.
    //
    // 2. If our self init call has a throwing function as an argument that
    //    actually throws.
    if (auto *SI = dyn_cast<StoreInst>(User)) {
      if (SI->getDest() == MUI) {
        SILValue src = SI->getSrc();

        // Look through conversions.
        while (auto conversion = ConversionOperation(src)) {
          src = conversion.getConverted();
        }

        if (auto *li = dyn_cast<LoadInst>(src)) {
          if (li->getOperand() == MUI) {
            continue;
          }
        }
      }
    }

    if (isUninitializedMetatypeInst(User))
      continue;

    UseInfo.trackUse(DIMemoryUse(User, Kind, 0, 1));
  }
}

//===----------------------------------------------------------------------===//
//                            Top Level Entrypoint
//===----------------------------------------------------------------------===//

static bool shouldPerformClassInitSelf(const DIMemoryObjectInfo &MemoryInfo) {
  if (MemoryInfo.isDelegatingSelfAllocated())
    return true;

  return MemoryInfo.isNonDelegatingInit() &&
         MemoryInfo.getASTType()->getClassOrBoundGenericClass() != nullptr &&
         MemoryInfo.isDerivedClassSelfOnly();
}

/// Analyze all uses of the specified allocation instruction (alloc_box,
/// alloc_stack or mark_uninitialized), classifying them and storing the
/// information found into the Uses and Releases lists.
void swift::ownership::collectDIElementUsesFrom(
    const DIMemoryObjectInfo &MemoryInfo, DIElementUseInfo &UseInfo) {

  if (shouldPerformClassInitSelf(MemoryInfo)) {
    ClassInitElementUseCollector UseCollector(MemoryInfo, UseInfo);
    UseCollector.collectClassInitSelfUses();
    gatherDestroysOfContainer(MemoryInfo, UseInfo);
    return;
  }

  if (MemoryInfo.isDelegatingInit()) {
    // When we're analyzing a delegating constructor, we aren't field sensitive
    // at all. Just treat all members of self as uses of the single
    // non-field-sensitive value.
    assert(MemoryInfo.getNumElements() == 1 &&
           "delegating inits only have 1 bit");
    collectDelegatingInitUses(MemoryInfo, UseInfo,
                              MemoryInfo.getUninitializedValue());
    gatherDestroysOfContainer(MemoryInfo, UseInfo);
    return;
  }

  ElementUseCollector::FunctionSet VisitedClosures;
  ElementUseCollector collector(MemoryInfo, UseInfo, VisitedClosures);
  collector.collectFrom(MemoryInfo.getUninitializedValue(),
                        /*collectDestroysOfContainer*/ true);
}