File: GenValueWitness.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 (1869 lines) | stat: -rw-r--r-- 75,822 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
//===--- GenValueWitness.cpp - IR generation for value witnesses ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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
//
//===----------------------------------------------------------------------===//
//
//  This file implements IR generation for value witnesses in Swift.
//
//  Value witnesses are (predominantly) functions that implement the basic
//  operations for copying and destroying values.
//
//  In the comments throughout this file, three type names are used:
//    'B' is the type of a fixed-size buffer
//    'T' is the type which implements a protocol
//
//===----------------------------------------------------------------------===//

#include "swift/AST/ASTContext.h"
#include "swift/AST/Attr.h"
#include "swift/AST/DiagnosticsIRGen.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/Types.h"
#include "swift/Basic/BlockList.h"
#include "swift/IRGen/Linking.h"
#include "swift/SIL/TypeLowering.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/Support/raw_ostream.h"

#include "ConstantBuilder.h"
#include "Explosion.h"
#include "FixedTypeInfo.h"
#include "GenEnum.h"
#include "GenMeta.h"
#include "GenOpaque.h"
#include "GenPointerAuth.h"
#include "IRGenDebugInfo.h"
#include "IRGenFunction.h"
#include "IRGenMangler.h"
#include "IRGenModule.h"
#include "MetadataLayout.h"
#include "StructLayout.h"
#include "TypeInfo.h"

#include "GenValueWitness.h"

using namespace swift;
using namespace irgen;

const char *irgen::getValueWitnessName(ValueWitness witness) {
  switch (witness) {
#define CASE(NAME) case ValueWitness::NAME: return #NAME;
  CASE(AssignWithCopy)
  CASE(AssignWithTake)
  CASE(Destroy)
  CASE(InitializeBufferWithCopyOfBuffer)
  CASE(InitializeWithCopy)
  CASE(InitializeWithTake)
  CASE(GetEnumTag)
  CASE(DestructiveProjectEnumData)
  CASE(DestructiveInjectEnumTag)
  CASE(Size)
  CASE(Flags)
  CASE(ExtraInhabitantCount)
  CASE(Stride)
  CASE(GetEnumTagSinglePayload)
  CASE(StoreEnumTagSinglePayload)
#undef CASE
  }
  llvm_unreachable("bad value witness kind");
}

namespace {
  /// An operation to be performed for various kinds of packing.
  struct DynamicPackingOperation {
    virtual ~DynamicPackingOperation() = default;

    /// Emit the operation at a concrete packing kind.
    ///
    /// Immediately after this call, there will be an unconditional
    /// branch to the continuation block.
    virtual void emitForPacking(IRGenFunction &IGF,
                                SILType T,
                                const TypeInfo &type,
                                FixedPacking packing) = 0;

    /// Given that we are currently at the beginning of the
    /// continuation block, complete the operation.
    virtual void complete(IRGenFunction &IGF) = 0;
  };

  /// A class for merging a particular kind of value across control flow.
  template <class T> class DynamicPackingPHIMapping;

  /// An implementation of DynamicPackingPHIMapping for a single LLVM value.
  template <> class DynamicPackingPHIMapping<llvm::Value*> {
    llvm::PHINode *PHI = nullptr;
  public:
    void collect(IRGenFunction &IGF, llvm::Value *value) {
      // Add the result to the phi, creating it (unparented) if necessary.
      if (!PHI) PHI = llvm::PHINode::Create(value->getType(), 2,
                                            "dynamic-packing.result");
      PHI->addIncoming(value, IGF.Builder.GetInsertBlock());
    }
    void complete(IRGenFunction &IGF) {
      assert(PHI);
      IGF.Builder.Insert(PHI);
    }
    llvm::Value *get(IRGenFunction &IGF, SILType T, const TypeInfo &type) {
      assert(PHI);
      return PHI;
    }
  };

  /// An implementation of DynamicPackingPHIMapping for Addresses.
  template <> class DynamicPackingPHIMapping<Address>
      : private DynamicPackingPHIMapping<llvm::Value*> {
    using super = DynamicPackingPHIMapping<llvm::Value *>;

  public:
    void collect(IRGenFunction &IGF, Address value) {
      super::collect(IGF, value.getAddress());
    }
    void complete(IRGenFunction &IGF) {
      super::complete(IGF);
    }
    Address get(IRGenFunction &IGF, SILType T, const TypeInfo &type) {
      return type.getAddressForPointer(super::get(IGF, T, type));
    }
  };

  /// An implementation of packing operations based around a lambda.
  template <class ResultTy, class FnTy>
  class LambdaDynamicPackingOperation : public DynamicPackingOperation {
    FnTy Fn;
    DynamicPackingPHIMapping<ResultTy> Mapping;
  public:
    explicit LambdaDynamicPackingOperation(FnTy &&fn) : Fn(fn) {}
    void emitForPacking(IRGenFunction &IGF, SILType T, const TypeInfo &type,
                        FixedPacking packing) override {
      Mapping.collect(IGF, Fn(IGF, T, type, packing));
    }

    void complete(IRGenFunction &IGF) override {
      Mapping.complete(IGF);
    }

    ResultTy get(IRGenFunction &IGF, SILType T, const TypeInfo &type) {
      return Mapping.get(IGF, T, type);
    }
  };

  /// A partial specialization for lambda-based packing operations
  /// that return 'void'.
  template <class FnTy>
  class LambdaDynamicPackingOperation<void, FnTy>
      : public DynamicPackingOperation {
    FnTy Fn;
  public:
    explicit LambdaDynamicPackingOperation(FnTy &&fn) : Fn(fn) {}
    void emitForPacking(IRGenFunction &IGF, SILType T, const TypeInfo &type,
                        FixedPacking packing) override {
      Fn(IGF, T, type, packing);
    }
    void complete(IRGenFunction &IGF) override {}
    void get(IRGenFunction &IGF, SILType T, const TypeInfo &type) {}
  };
} // end anonymous namespace

/// Dynamic check for the enabling conditions of different kinds of
/// packing into a fixed-size buffer, and perform an operation at each
/// of them.
static void emitDynamicPackingOperation(IRGenFunction &IGF,
                                        SILType T,
                                        const TypeInfo &type,
                                        DynamicPackingOperation &operation) {
  auto indirectBB = IGF.createBasicBlock("dynamic-packing.indirect");
  auto directBB = IGF.createBasicBlock("dynamic-packing.direct");
  auto contBB = IGF.createBasicBlock("dynamic-packing.cont");

  // Branch.
  auto isInline = type.isDynamicallyPackedInline(IGF, T);
  IGF.Builder.CreateCondBr(isInline, directBB, indirectBB);

  // Emit the indirect path.
  IGF.Builder.emitBlock(indirectBB); {
    ConditionalDominanceScope condition(IGF);
    operation.emitForPacking(IGF, T, type, FixedPacking::Allocate);
    IGF.Builder.CreateBr(contBB);
  }

  // Emit the direct path.
  IGF.Builder.emitBlock(directBB); {
    ConditionalDominanceScope condition(IGF);
    operation.emitForPacking(IGF, T, type, FixedPacking::OffsetZero);
    IGF.Builder.CreateBr(contBB);
  }

  // Enter the continuation block and add the PHI if required.
  IGF.Builder.emitBlock(contBB);
  operation.complete(IGF);
}

/// A helper function for creating a lambda-based DynamicPackingOperation.
template <class ResultTy, class FnTy>
LambdaDynamicPackingOperation<ResultTy, FnTy>
makeLambdaDynamicPackingOperation(FnTy &&fn) {
  return LambdaDynamicPackingOperation<ResultTy, FnTy>(std::move(fn));
}

/// Perform an operation on a type that requires dynamic packing.
template <class ResultTy, class... ArgTys, class... ParamTys>
static ResultTy emitForDynamicPacking(IRGenFunction &IGF,
                                      ResultTy (*fn)(ParamTys...),
                                      SILType T,
                                      const TypeInfo &type,
                                      ArgTys... args) {
  auto operation = makeLambdaDynamicPackingOperation<ResultTy>(
    [&](IRGenFunction &IGF, SILType T, const TypeInfo &type,
        FixedPacking packing) {
      return fn(IGF, args..., T, type, packing);
    });
  emitDynamicPackingOperation(IGF, T, type, operation);
  return operation.get(IGF, T, type);
}

/// Emit a 'projectBuffer' operation.  Always returns a T*.
static Address emitDefaultProjectBuffer(IRGenFunction &IGF, Address buffer,
                                        SILType T, const TypeInfo &type,
                                        FixedPacking packing) {
  llvm::PointerType *resultTy = type.getStorageType()->getPointerTo();
  switch (packing) {
  case FixedPacking::Allocate: {

    // Use copy-on-write existentials?
    auto &IGM = IGF.IGM;
    auto &Builder = IGF.Builder;
    Address boxAddress(
        Builder.CreateBitCast(buffer.getAddress(),
                              IGM.RefCountedPtrTy->getPointerTo()),
        IGM.RefCountedPtrTy, buffer.getAlignment());
    auto *boxStart = IGF.Builder.CreateLoad(boxAddress);
    auto *alignmentMask = type.getAlignmentMask(IGF, T);
    auto *heapHeaderSize = llvm::ConstantInt::get(
        IGM.SizeTy, IGM.RefCountedStructSize.getValue());
    auto *startOffset =
        Builder.CreateAnd(Builder.CreateAdd(heapHeaderSize, alignmentMask),
                          Builder.CreateNot(alignmentMask));
    auto *addressInBox =
        IGF.emitByteOffsetGEP(boxStart, startOffset, IGM.OpaqueTy);

    addressInBox = Builder.CreateBitCast(addressInBox, resultTy);
    return type.getAddressForPointer(addressInBox);
  }

  case FixedPacking::OffsetZero: {
    return IGF.Builder.CreateElementBitCast(buffer, type.getStorageType(),
                                            "object");
  }

  case FixedPacking::Dynamic:
    return emitForDynamicPacking(IGF, &emitDefaultProjectBuffer,
                                 T, type, buffer);

  }
  llvm_unreachable("bad packing!");

}

/// Emit an 'allocateBuffer' operation.  Always returns a T*.
static Address emitDefaultAllocateBuffer(IRGenFunction &IGF, Address buffer,
                                         SILType T, const TypeInfo &type,
                                         FixedPacking packing) {
  switch (packing) {
  case FixedPacking::Allocate: {
    llvm::Value *box, *address;
    auto *metadata = IGF.emitTypeMetadataRefForLayout(T);
    IGF.emitAllocBoxCall(metadata, box, address);
    IGF.Builder.CreateStore(
        box, Address(IGF.Builder.CreateBitCast(buffer.getAddress(),
                                               box->getType()->getPointerTo()),
                     IGF.IGM.RefCountedPtrTy, buffer.getAlignment()));

    llvm::PointerType *resultTy = type.getStorageType()->getPointerTo();
    address = IGF.Builder.CreateBitCast(address, resultTy);
    return type.getAddressForPointer(address);
  }

  case FixedPacking::OffsetZero:
    return emitDefaultProjectBuffer(IGF, buffer, T, type, packing);

  case FixedPacking::Dynamic:
    return emitForDynamicPacking(IGF, &emitDefaultAllocateBuffer,
                                 T, type, buffer);
  }
  llvm_unreachable("bad packing!");
}

/// Emit an 'initializeBufferWithCopyOfBuffer' operation.
/// Returns the address of the destination object.
static Address emitDefaultInitializeBufferWithCopyOfBuffer(
    IRGenFunction &IGF, Address destBuffer, Address srcBuffer, SILType T,
    const TypeInfo &type, FixedPacking packing) {
  // Special-case dynamic packing in order to thread the jumps.
  if (packing == FixedPacking::Dynamic)
    return emitForDynamicPacking(IGF,
                                 &emitDefaultInitializeBufferWithCopyOfBuffer,
                                 T, type, destBuffer, srcBuffer);

  if (packing == FixedPacking::OffsetZero) {
    Address destObject =
        emitDefaultAllocateBuffer(IGF, destBuffer, T, type, packing);
    Address srcObject =
        emitDefaultProjectBuffer(IGF, srcBuffer, T, type, packing);
    type.initializeWithCopy(IGF, destObject, srcObject, T, true);
    return destObject;
  } else {
    assert(packing == FixedPacking::Allocate);
    auto *destReferenceAddr = IGF.Builder.CreateBitCast(
        destBuffer.getAddress(), IGF.IGM.RefCountedPtrTy->getPointerTo());
    auto *srcReferenceAddr = IGF.Builder.CreateBitCast(
        srcBuffer.getAddress(), IGF.IGM.RefCountedPtrTy->getPointerTo());
    auto *srcReference = IGF.Builder.CreateLoad(Address(
        srcReferenceAddr, IGF.IGM.RefCountedPtrTy, srcBuffer.getAlignment()));
    IGF.emitNativeStrongRetain(srcReference, IGF.getDefaultAtomicity());
    IGF.Builder.CreateStore(srcReference,
                            Address(destReferenceAddr, IGF.IGM.RefCountedPtrTy,
                                    destBuffer.getAlignment()));
    return emitDefaultProjectBuffer(IGF, destBuffer, T, type, packing);
  }
}

// Metaprogram some of the common boilerplate here:
//   - the default implementation in TypeInfo
//   - the value-witness emitter which tries to avoid some dynamic
//     dispatch and the recomputation of the fixed packing

#define DEFINE_BINARY_BUFFER_OP(LOWER, TITLE)                             \
Address TypeInfo::LOWER(IRGenFunction &IGF, Address dest, Address src,    \
                        SILType T) const {                                \
  return emitDefault##TITLE(IGF, dest, src, T, *this,                     \
                            getFixedPacking(IGF.IGM));                    \
}                                                                         \
static Address emit##TITLE(IRGenFunction &IGF, Address dest, Address src, \
                           SILType T, const TypeInfo &type,               \
                           FixedPacking packing) {                        \
  if (packing == FixedPacking::Dynamic)                                   \
    return type.LOWER(IGF, dest, src, T);                                 \
  return emitDefault##TITLE(IGF, dest, src, T, type, packing);            \
}
DEFINE_BINARY_BUFFER_OP(initializeBufferWithCopyOfBuffer,
                        InitializeBufferWithCopyOfBuffer)
#undef DEFINE_BINARY_BUFFER_OP


static llvm::Value *getArg(llvm::Function::arg_iterator &it,
                           StringRef name) {
  llvm::Value *arg = &*(it++);
  arg->setName(name);
  return arg;
}

/// Get the next argument as a pointer to the given storage type.
static Address getArgAs(IRGenFunction &IGF,
                        llvm::Function::arg_iterator &it,
                        const TypeInfo &type,
                        StringRef name) {
  llvm::Value *arg = getArg(it, name);
  llvm::Value *result =
    IGF.Builder.CreateBitCast(arg, type.getStorageType()->getPointerTo());
  return type.getAddressForPointer(result);
}

/// Get the next argument as a pointer to the given storage type.
static Address getArgAsBuffer(IRGenFunction &IGF,
                              llvm::Function::arg_iterator &it,
                              StringRef name) {
  llvm::Value *arg = getArg(it, name);
  return Address(arg, IGF.IGM.getFixedBufferTy(),
                 getFixedBufferAlignment(IGF.IGM));
}

/// Don't add new callers of this, it doesn't make any sense.
static CanType getFormalTypeInPrimaryContext(CanType abstractType) {
  auto *nominal = abstractType.getAnyNominal();
  if (nominal && abstractType->isEqual(nominal->getDeclaredType())) {
    return nominal->mapTypeIntoContext(nominal->getDeclaredInterfaceType())
      ->getCanonicalType();
  }

  assert(!abstractType->hasUnboundGenericType());
  return abstractType;
}

SILType irgen::getLoweredTypeInPrimaryContext(IRGenModule &IGM,
                                              NominalTypeDecl *type) {
  CanType concreteFormalType = type->mapTypeIntoContext(
      type->getDeclaredInterfaceType())->getCanonicalType();
  return IGM.getLoweredType(concreteFormalType);
}

void irgen::getArgAsLocalSelfTypeMetadata(IRGenFunction &IGF, llvm::Value *arg,
                                          CanType abstractType) {
  assert(arg->getType() == IGF.IGM.TypeMetadataPtrTy &&
         "Self argument is not a type?!");

  auto formalType = getFormalTypeInPrimaryContext(abstractType);
  IGF.bindLocalTypeDataFromTypeMetadata(formalType, IsExact, arg,
                                        MetadataState::Complete);
}

/// Get the next argument and use it as the 'self' type metadata.
static void getArgAsLocalSelfTypeMetadata(IRGenFunction &IGF,
                                          llvm::Function::arg_iterator &it,
                                          CanType abstractType) {
  llvm::Value *arg = &*it++;
  getArgAsLocalSelfTypeMetadata(IGF, arg, abstractType);
}

static const TypeLayoutEntry *
conditionallyGetTypeLayoutEntry(IRGenModule &IGM, SILType concreteType) {
  if (!IGM.getOptions().UseTypeLayoutValueHandling)
    return nullptr;

  auto &typeLayoutEntry = IGM.getTypeLayoutEntry(
    concreteType, IGM.getOptions().ForceStructTypeLayouts);

  // Don't use type layout based generation for layouts that contain a resilient
  // field but no archetype. We don't expect a speedup by using type layout
  // based ir generation.
  if ((typeLayoutEntry.containsResilientField() &&
       !typeLayoutEntry.containsArchetypeField()) ||
      typeLayoutEntry.containsDependentResilientField())
    return nullptr;

  return &typeLayoutEntry;
}

static const EnumTypeLayoutEntry *
conditionallyGetEnumTypeLayoutEntry(IRGenModule &IGM, SILType concreteType) {
  auto *entry = conditionallyGetTypeLayoutEntry(IGM, concreteType);
  if (!entry)
    return nullptr;

  return entry->getAsEnum();
}

/// Build a specific value-witness function.
static void buildValueWitnessFunction(IRGenModule &IGM,
                                      llvm::Function *fn,
                                      ValueWitness index,
                                      FixedPacking packing,
                                      CanType abstractType,
                                      SILType concreteType,
                                      const TypeInfo &type) {
  assert(isValueWitnessFunction(index));

  IRGenFunction IGF(IGM, fn);
  if (IGM.DebugInfo)
    IGM.DebugInfo->emitArtificialFunction(IGF, fn);

  auto argv = fn->arg_begin();
  switch (index) {
  case ValueWitness::AssignWithCopy: {
    Address dest = getArgAs(IGF, argv, type, "dest");
    Address src = getArgAs(IGF, argv, type, "src");
    getArgAsLocalSelfTypeMetadata(IGF, argv, abstractType);
    if (auto *typeLayoutEntry =
            conditionallyGetTypeLayoutEntry(IGM, concreteType)) {
      typeLayoutEntry->assignWithCopy(IGF, dest, src);
    } else {
      type.assignWithCopy(IGF, dest, src, concreteType, true);
    }
    dest = IGF.Builder.CreateElementBitCast(dest, IGF.IGM.OpaqueTy);
    IGF.Builder.CreateRet(dest.getAddress());
    return;
  }

  case ValueWitness::AssignWithTake: {
    Address dest = getArgAs(IGF, argv, type, "dest");
    Address src = getArgAs(IGF, argv, type, "src");
    getArgAsLocalSelfTypeMetadata(IGF, argv, abstractType);
    if (auto *typeLayoutEntry =
            conditionallyGetTypeLayoutEntry(IGM, concreteType)) {
      typeLayoutEntry->assignWithTake(IGF, dest, src);
    } else {
      type.assignWithTake(IGF, dest, src, concreteType, true);
    }
    dest = IGF.Builder.CreateElementBitCast(dest, IGF.IGM.OpaqueTy);
    IGF.Builder.CreateRet(dest.getAddress());
    return;
  }

  case ValueWitness::Destroy: {
    Address object = getArgAs(IGF, argv, type, "object");
    getArgAsLocalSelfTypeMetadata(IGF, argv, abstractType);
    if (auto *typeLayoutEntry =
            conditionallyGetTypeLayoutEntry(IGM, concreteType)) {
      typeLayoutEntry->destroy(IGF, object);
    } else {
      type.destroy(IGF, object, concreteType, true);
    }
    IGF.Builder.CreateRetVoid();
    return;
  }

  case ValueWitness::InitializeBufferWithCopyOfBuffer: {
    Address dest = getArgAsBuffer(IGF, argv, "dest");
    Address src = getArgAsBuffer(IGF, argv, "src");
    getArgAsLocalSelfTypeMetadata(IGF, argv, abstractType);

    llvm::Value *objectPtr = nullptr;
    if (auto *typeLayoutEntry =
            conditionallyGetTypeLayoutEntry(IGM, concreteType)) {
      objectPtr = typeLayoutEntry->initBufferWithCopyOfBuffer(IGF, dest, src);
    } else {
      Address result = emitInitializeBufferWithCopyOfBuffer(
          IGF, dest, src, concreteType, type, packing);
      result = IGF.Builder.CreateElementBitCast(result, IGF.IGM.OpaqueTy);
      objectPtr = result.getAddress();
    }
    IGF.Builder.CreateRet(objectPtr);
    return;
  }

  case ValueWitness::InitializeWithCopy: {
    Address dest = getArgAs(IGF, argv, type, "dest");
    Address src = getArgAs(IGF, argv, type, "src");
    getArgAsLocalSelfTypeMetadata(IGF, argv, abstractType);
    if (auto *typeLayoutEntry =
            conditionallyGetTypeLayoutEntry(IGM, concreteType)) {
      typeLayoutEntry->initWithCopy(IGF, dest, src);
    } else {
      type.initializeWithCopy(IGF, dest, src, concreteType, true);
    }
    dest = IGF.Builder.CreateElementBitCast(dest, IGF.IGM.OpaqueTy);
    IGF.Builder.CreateRet(dest.getAddress());
    return;
  }

  case ValueWitness::InitializeWithTake: {
    Address dest = getArgAs(IGF, argv, type, "dest");
    Address src = getArgAs(IGF, argv, type, "src");
    getArgAsLocalSelfTypeMetadata(IGF, argv, abstractType);

    if (auto *typeLayoutEntry =
            conditionallyGetTypeLayoutEntry(IGM, concreteType)) {
      typeLayoutEntry->initWithTake(IGF, dest, src);
    } else {
      type.initializeWithTake(IGF, dest, src, concreteType, true);
    }
    dest = IGF.Builder.CreateElementBitCast(dest, IGF.IGM.OpaqueTy);
    IGF.Builder.CreateRet(dest.getAddress());
    return;
  }

  case ValueWitness::GetEnumTag: {
    auto &strategy = getEnumImplStrategy(IGM, concreteType);

    llvm::Value *value = getArg(argv, "value");
    getArgAsLocalSelfTypeMetadata(IGF, argv, abstractType);

    auto enumTy = type.getStorageType()->getPointerTo();
    value = IGF.Builder.CreateBitCast(value, enumTy);
    auto enumAddr = type.getAddressForPointer(value);

    llvm::Value *result;
    if (auto *enumTypeLayoutEntry =
            conditionallyGetEnumTypeLayoutEntry(IGM, concreteType)) {
      result = enumTypeLayoutEntry->getEnumTag(IGF, enumAddr);
    } else {
      result = strategy.emitGetEnumTag(IGF, concreteType, enumAddr);
    }
    IGF.Builder.CreateRet(result);
    return;
  }

  case ValueWitness::DestructiveProjectEnumData: {
    auto &strategy = getEnumImplStrategy(IGM, concreteType);

    llvm::Value *value = getArg(argv, "value");
    getArgAsLocalSelfTypeMetadata(IGF, argv, abstractType);

    if (!strategy.getElementsWithPayload().empty()) {
      if (auto *enumTypeLayoutEntry =
              conditionallyGetEnumTypeLayoutEntry(IGM, concreteType)) {
        enumTypeLayoutEntry->destructiveProjectEnumData(
            IGF, Address(value, IGM.OpaqueTy, type.getBestKnownAlignment()));
      } else {
        strategy.destructiveProjectDataForLoad(
            IGF, concreteType,
            Address(value, IGM.OpaqueTy, type.getBestKnownAlignment()));
      }
    }

    IGF.Builder.CreateRetVoid();
    return;
  }

  case ValueWitness::DestructiveInjectEnumTag: {
    auto &strategy = getEnumImplStrategy(IGM, concreteType);

    llvm::Value *value = getArg(argv, "value");

    auto enumTy = type.getStorageType()->getPointerTo();
    value = IGF.Builder.CreateBitCast(value, enumTy);

    llvm::Value *tag = getArg(argv, "tag");

    getArgAsLocalSelfTypeMetadata(IGF, argv, abstractType);
    if (auto *enumTypeLayoutEntry =
            conditionallyGetEnumTypeLayoutEntry(IGM, concreteType)) {
      enumTypeLayoutEntry->destructiveInjectEnumTag(
          IGF, tag,
          Address(value, type.getStorageType(), type.getBestKnownAlignment()));
    } else {
      strategy.emitStoreTag(
          IGF, concreteType,
          Address(value, type.getStorageType(), type.getBestKnownAlignment()),
          tag);
    }

    IGF.Builder.CreateRetVoid();
    return;
  }

  case ValueWitness::GetEnumTagSinglePayload: {
    llvm::Value *value = getArg(argv, "value");
    auto enumTy = type.getStorageType()->getPointerTo();
    value = IGF.Builder.CreateBitCast(value, enumTy);

    llvm::Value *numEmptyCases = getArg(argv, "numEmptyCases");

    getArgAsLocalSelfTypeMetadata(IGF, argv, abstractType);
    if (auto *typeLayoutEntry =
            conditionallyGetTypeLayoutEntry(IGM, concreteType)) {
      auto *idx = typeLayoutEntry->getEnumTagSinglePayload(
          IGF, numEmptyCases,
          Address(value, type.getStorageType(), type.getBestKnownAlignment()));
      IGF.Builder.CreateRet(idx);
    } else {
      llvm::Value *idx = type.getEnumTagSinglePayload(
          IGF, numEmptyCases,
          Address(value, type.getStorageType(), type.getBestKnownAlignment()),
          concreteType, true);
      IGF.Builder.CreateRet(idx);
    }

    return;
  }

  case ValueWitness::StoreEnumTagSinglePayload: {
    llvm::Value *value = getArg(argv, "value");
    auto enumTy = type.getStorageType()->getPointerTo();
    value = IGF.Builder.CreateBitCast(value, enumTy);

    llvm::Value *whichCase = getArg(argv, "whichCase");
    llvm::Value *numEmptyCases = getArg(argv, "numEmptyCases");

    getArgAsLocalSelfTypeMetadata(IGF, argv, abstractType);
    if (auto *typeLayoutEntry =
            conditionallyGetTypeLayoutEntry(IGM, concreteType)) {
      typeLayoutEntry->storeEnumTagSinglePayload(
          IGF, whichCase, numEmptyCases,
          Address(value, type.getStorageType(), type.getBestKnownAlignment()));
    } else {
      type.storeEnumTagSinglePayload(
          IGF, whichCase, numEmptyCases,
          Address(value, type.getStorageType(), type.getBestKnownAlignment()),
          concreteType, true);
    }
    IGF.Builder.CreateRetVoid();
    return;
  }

  case ValueWitness::Size:
  case ValueWitness::Flags:
  case ValueWitness::ExtraInhabitantCount:
  case ValueWitness::Stride:
    llvm_unreachable("these value witnesses aren't functions");
  }
  llvm_unreachable("bad value witness kind!");
}

/// Return a function which takes two pointer arguments and returns
/// void immediately.
static llvm::Constant *getNoOpVoidFunction(IRGenModule &IGM) {
  llvm::Type *argTys[] = { IGM.Int8PtrTy, IGM.TypeMetadataPtrTy };
  return IGM.getOrCreateHelperFunction("__swift_noop_void_return",
                                       IGM.VoidTy, argTys,
                                       [&](IRGenFunction &IGF) {
    IGF.Builder.CreateRetVoid();
  });
}

/// Return a function that traps because of an attempt to copy a noncopyable
/// type.
static llvm::Constant *getNoncopyableTrapFunction(IRGenModule &IGM) {
  return IGM.getOrCreateHelperFunction("__swift_cannot_copy_noncopyable_type",
                                       IGM.VoidTy, {},
                                       [&](IRGenFunction &IGF) {
    IGF.Builder.CreateNonMergeableTrap(IGM, "attempt to copy a value of a type that cannot be copied");
    IGF.Builder.CreateUnreachable();
  });
}

/// Return a function which takes three pointer arguments and does a
/// retaining assignWithCopy on the first two: it loads a pointer from
/// the second, retains it, loads a pointer from the first, stores the
/// new pointer in the first, and releases the old pointer.
static llvm::Constant *getAssignWithCopyStrongFunction(IRGenModule &IGM) {
  llvm::Type *ptrPtrTy = IGM.RefCountedPtrTy->getPointerTo();
  llvm::Type *argTys[] = { ptrPtrTy, ptrPtrTy, IGM.WitnessTablePtrTy };
  return IGM.getOrCreateHelperFunction("__swift_assignWithCopy_strong",
                                       ptrPtrTy, argTys,
                                       [&](IRGenFunction &IGF) {
    auto it = IGF.CurFn->arg_begin();
    Address dest(&*(it++), IGM.RefCountedPtrTy, IGM.getPointerAlignment());
    Address src(&*(it++), IGM.RefCountedPtrTy, IGM.getPointerAlignment());

    llvm::Value *newValue = IGF.Builder.CreateLoad(src, "new");
    IGF.emitNativeStrongRetain(newValue, IGF.getDefaultAtomicity());
    llvm::Value *oldValue = IGF.Builder.CreateLoad(dest, "old");
    IGF.Builder.CreateStore(newValue, dest);
    IGF.emitNativeStrongRelease(oldValue, IGF.getDefaultAtomicity());

    IGF.Builder.CreateRet(dest.getAddress());
  });
}

/// Return a function which takes three pointer arguments and does a
/// retaining assignWithTake on the first two: it loads a pointer from
/// the second, retains it, loads a pointer from the first, stores the
/// new pointer in the first, and releases the old pointer.
static llvm::Constant *getAssignWithTakeStrongFunction(IRGenModule &IGM) {
  llvm::Type *ptrPtrTy = IGM.RefCountedPtrTy->getPointerTo();
  llvm::Type *argTys[] = { ptrPtrTy, ptrPtrTy, IGM.WitnessTablePtrTy };
  return IGM.getOrCreateHelperFunction("__swift_assignWithTake_strong",
                                       ptrPtrTy, argTys,
                                       [&](IRGenFunction &IGF) {
    auto it = IGF.CurFn->arg_begin();
    Address dest(&*(it++), IGM.RefCountedPtrTy, IGM.getPointerAlignment());
    Address src(&*(it++), IGM.RefCountedPtrTy, IGM.getPointerAlignment());

    llvm::Value *newValue = IGF.Builder.CreateLoad(src, "new");
    llvm::Value *oldValue = IGF.Builder.CreateLoad(dest, "old");
    IGF.Builder.CreateStore(newValue, dest);
    IGF.emitNativeStrongRelease(oldValue, IGF.getDefaultAtomicity());

    IGF.Builder.CreateRet(dest.getAddress());
  });
}

/// Return a function which takes three pointer arguments and does a
/// retaining initWithCopy on the first two: it loads a pointer from
/// the second, retains it, and stores that in the first.
static llvm::Constant *getInitWithCopyStrongFunction(IRGenModule &IGM) {
  llvm::Type *ptrPtrTy = IGM.RefCountedPtrTy->getPointerTo();
  llvm::Type *argTys[] = { ptrPtrTy, ptrPtrTy, IGM.WitnessTablePtrTy };
  return IGM.getOrCreateHelperFunction("__swift_initWithCopy_strong",
                                       ptrPtrTy, argTys,
                                       [&](IRGenFunction &IGF) {
    auto it = IGF.CurFn->arg_begin();
    Address dest(&*(it++), IGM.RefCountedPtrTy, IGM.getPointerAlignment());
    Address src(&*(it++), IGM.RefCountedPtrTy, IGM.getPointerAlignment());

    llvm::Value *newValue = IGF.Builder.CreateLoad(src, "new");
    IGF.emitNativeStrongRetain(newValue, IGF.getDefaultAtomicity());
    IGF.Builder.CreateStore(newValue, dest);

    IGF.Builder.CreateRet(dest.getAddress());
  });
}

/// Return a function which takes two pointer arguments, loads a
/// pointer from the first, and calls swift_release on it immediately.
static llvm::Constant *getDestroyStrongFunction(IRGenModule &IGM) {
  llvm::Type *argTys[] = { IGM.Int8PtrPtrTy, IGM.WitnessTablePtrTy };
  return IGM.getOrCreateHelperFunction(
      "__swift_destroy_strong", IGM.VoidTy, argTys, [&](IRGenFunction &IGF) {
        Address arg(&*IGF.CurFn->arg_begin(), IGM.Int8PtrTy,
                    IGM.getPointerAlignment());
        IGF.emitNativeStrongRelease(IGF.Builder.CreateLoad(arg),
                                    IGF.getDefaultAtomicity());
        IGF.Builder.CreateRetVoid();
      });
}

/// Return a function which takes two pointer arguments, memcpys
/// from the second to the first, and returns the first argument.
static llvm::Constant *getMemCpyFunction(IRGenModule &IGM,
                                         const TypeInfo &objectTI) {
  // If we don't have a fixed type, use the standard copy-opaque-POD
  // routine.  It's not quite clear how in practice we'll be able to
  // conclude that something is known-POD without knowing its size,
  // but it's (1) conceivable and (2) needed as a general export anyway.
  auto *fixedTI = dyn_cast<FixedTypeInfo>(&objectTI);
  if (!fixedTI) return IGM.getCopyPODFn();

  // We need to unique by both size and alignment.  Note that we're
  // assuming that it's safe to call a function that returns a pointer
  // at a site that assumes the function returns void.
  llvm::SmallString<40> name;
  {
    llvm::raw_svector_ostream nameStream(name);
    nameStream << "__swift_memcpy";
    nameStream << fixedTI->getFixedSize().getValue();
    nameStream << '_';
    nameStream << fixedTI->getFixedAlignment().getValue();
  }

  llvm::Type *argTys[] = { IGM.Int8PtrTy, IGM.Int8PtrTy, IGM.TypeMetadataPtrTy };
  return IGM.getOrCreateHelperFunction(name, IGM.Int8PtrTy, argTys,
                                       [&](IRGenFunction &IGF) {
    auto it = IGF.CurFn->arg_begin();
    Address dest(&*it++, IGM.Int8Ty, fixedTI->getFixedAlignment());
    Address src(&*it++, IGM.Int8Ty, fixedTI->getFixedAlignment());
    IGF.emitMemCpy(dest, src, fixedTI->getFixedSize());
    IGF.Builder.CreateRet(dest.getAddress());
  });
}

namespace {
struct BoundGenericTypeCharacteristics {
  SILType concreteType;
  const TypeInfo *TI;
  FixedPacking packing;
};

ValueWitnessFlags getValueWitnessFlags(const TypeInfo *TI, SILType concreteType,
                                       FixedPacking packing) {
  ValueWitnessFlags flags;

  // If we locally know that the type has fixed layout, we can emit
  // meaningful flags for it.
  if (auto *fixedTI = dyn_cast<FixedTypeInfo>(TI)) {
    assert(packing == FixedPacking::OffsetZero ||
           packing == FixedPacking::Allocate);
    bool isInline = packing == FixedPacking::OffsetZero;
    bool isBitwiseTakable =
        fixedTI->isBitwiseTakable(ResilienceExpansion::Maximal);
    bool isBitwiseBorrowable =
        fixedTI->isBitwiseBorrowable(ResilienceExpansion::Maximal);
    assert(isBitwiseTakable || !isInline);
    flags = flags.withAlignment(fixedTI->getFixedAlignment().getValue())
                .withPOD(fixedTI->isTriviallyDestroyable(ResilienceExpansion::Maximal))
                .withCopyable(fixedTI->isCopyable(ResilienceExpansion::Maximal))
                .withInlineStorage(isInline)
                .withBitwiseTakable(isBitwiseTakable)
                // the IsNotBitwiseBorrowable bit only needs to be set if the
                // type is bitwise-takable but not bitwise-borrowable, since
                // a type must be bitwise-takable to be bitwise-borrowable.
                //
                // Swift prior to version 6 didn't have the
                // IsNotBitwiseBorrowable bit, so to avoid unnecessary variation
                // in metadata output, we only set the bit when needed.
                .withBitwiseBorrowable(!isBitwiseTakable || isBitwiseBorrowable);
  } else {
    flags = flags.withIncomplete(true);
  }

  if (concreteType.getEnumOrBoundGenericEnum())
    flags = flags.withEnumWitnesses(true);

  return flags;
}

unsigned getExtraInhabitantCount(const TypeInfo *TI, IRGenModule &IGM) {
  unsigned value = 0;
  if (auto *fixedTI = dyn_cast<FixedTypeInfo>(TI)) {
    value = fixedTI->getFixedExtraInhabitantCount(IGM);
  }
  return value;
}

void addSize(ConstantStructBuilder &B, const TypeInfo *TI, IRGenModule &IGM) {
  if (auto staticSize = TI->getStaticSize(IGM))
    return B.add(staticSize);
  // Just fill in 0 here if the type can't be statically laid out.
  return B.addSize(Size(0));
}

void addStride(ConstantStructBuilder &B, const TypeInfo *TI, IRGenModule &IGM) {
  if (auto value = TI->getStaticStride(IGM))
    return B.add(value);

  // Just fill in null here if the type can't be statically laid out.
  return B.addSize(Size(0));
}
} // end anonymous namespace

bool irgen::layoutStringsEnabled(IRGenModule &IGM, bool diagnose) {
  auto moduleName = IGM.getSwiftModule()->getRealName().str();
  if (IGM.Context.blockListConfig.hasBlockListAction(
          moduleName, BlockListKeyKind::ModuleName,
          BlockListAction::ShouldUseLayoutStringValueWitnesses)) {
    if (diagnose) {
      IGM.Context.Diags.diagnose(SourceLoc(), diag::layout_strings_blocked,
                                 moduleName);
    }
    return false;
  }

  return IGM.Context.LangOpts.hasFeature(Feature::LayoutStringValueWitnesses) &&
         IGM.getOptions().EnableLayoutStringValueWitnesses;
}

static bool isRuntimeInstatiatedLayoutString(IRGenModule &IGM,
                                       const TypeLayoutEntry *typeLayoutEntry) {

  if (layoutStringsEnabled(IGM) &&
      IGM.Context.LangOpts.hasFeature(
          Feature::LayoutStringValueWitnessesInstantiation) &&
      IGM.getOptions().EnableLayoutStringValueWitnessesInstantiation) {
    return (
        (typeLayoutEntry->isAlignedGroup() || typeLayoutEntry->getAsEnum()) &&
        !typeLayoutEntry->isFixedSize(IGM));
  }

  return false;
}

static llvm::Constant *getEnumTagFunction(IRGenModule &IGM,
                                     const EnumTypeLayoutEntry *typeLayoutEntry,
                                          GenericSignature genericSig) {
  if (!typeLayoutEntry->layoutString(IGM, genericSig) &&
      !isRuntimeInstatiatedLayoutString(IGM, typeLayoutEntry)) {
    return nullptr;
  } else if (typeLayoutEntry->copyDestroyKind(IGM) !=
             EnumTypeLayoutEntry::CopyDestroyStrategy::Normal) {
    return nullptr;
  } else if (typeLayoutEntry->isSingleton()) {
    return IGM.getSingletonEnumGetEnumTagFn();
  } else if (!typeLayoutEntry->isFixedSize(IGM)) {
    if (typeLayoutEntry->isMultiPayloadEnum()) {
      return IGM.getMultiPayloadEnumGenericGetEnumTagFn();
    } else {
      return IGM.getSinglePayloadEnumGenericGetEnumTagFn();
    }
  } else if (typeLayoutEntry->isMultiPayloadEnum()) {
    return IGM.getEnumFnGetEnumTagFn();
  } else {
    auto &payloadTI = **(typeLayoutEntry->cases[0]->getFixedTypeInfo());
    auto mask = payloadTI.getFixedExtraInhabitantMask(IGM);
    auto tzCount = mask.countTrailingZeros();
    auto shiftedMask = mask.lshr(tzCount);
    // auto toCount = shiftedMask.countTrailingOnes();
    // if (payloadTI.mayHaveExtraInhabitants(IGM) &&
    //     (mask.popcount() > 64 ||
    //      toCount != mask.popcount() ||
    //      (tzCount % toCount != 0))) {
      return IGM.getEnumFnGetEnumTagFn();
    // } else {
    //   return IGM.getEnumSimpleGetEnumTagFn();
    // }
  }
}

static llvm::Constant *
getDestructiveInjectEnumTagFunction(IRGenModule &IGM,
                                    const EnumTypeLayoutEntry *typeLayoutEntry,
                                    GenericSignature genericSig) {
  if ((!typeLayoutEntry->layoutString(IGM, genericSig) &&
       !isRuntimeInstatiatedLayoutString(IGM, typeLayoutEntry))) {
    return nullptr;
  } else if (typeLayoutEntry->copyDestroyKind(IGM) !=
             EnumTypeLayoutEntry::CopyDestroyStrategy::Normal) {
    return nullptr;
  } else if (typeLayoutEntry->isSingleton()) {
    return IGM.getSingletonEnumDestructiveInjectEnumTagFn();
  } else if (!typeLayoutEntry->isFixedSize(IGM)) {
    if (typeLayoutEntry->isMultiPayloadEnum()) {
      return IGM.getMultiPayloadEnumGenericDestructiveInjectEnumTagFn();
    } else {
      return IGM.getSinglePayloadEnumGenericDestructiveInjectEnumTagFn();
    }
  } else if (typeLayoutEntry->isMultiPayloadEnum()) {
    return nullptr;
  } else {
    auto &payloadTI = **(typeLayoutEntry->cases[0]->getFixedTypeInfo());
    auto mask = payloadTI.getFixedExtraInhabitantMask(IGM);
    auto tzCount = mask.countTrailingZeros();
    auto shiftedMask = mask.lshr(tzCount);
    // auto toCount = shiftedMask.countTrailingOnes();
    // if (payloadTI.mayHaveExtraInhabitants(IGM) &&
    //     (mask.popcount() > 64 || toCount != mask.popcount() ||
    //      (tzCount % toCount != 0))) {
      return nullptr;
    // } else {
    //   return IGM.getEnumSimpleDestructiveInjectEnumTagFn();
    // }
  }
}

static bool
valueWitnessRequiresCopyability(ValueWitness index) {
  switch (index) {
  case ValueWitness::InitializeBufferWithCopyOfBuffer:
  case ValueWitness::InitializeWithCopy:
  case ValueWitness::AssignWithCopy:
    return true;
  
  case ValueWitness::Destroy:
  case ValueWitness::InitializeWithTake:
  case ValueWitness::AssignWithTake:
  case ValueWitness::GetEnumTagSinglePayload:
  case ValueWitness::StoreEnumTagSinglePayload:
  case ValueWitness::Size:
  case ValueWitness::Stride:
  case ValueWitness::Flags:
  case ValueWitness::ExtraInhabitantCount:
  case ValueWitness::GetEnumTag:
  case ValueWitness::DestructiveProjectEnumData:
  case ValueWitness::DestructiveInjectEnumTag:
    return false;
  }
  llvm_unreachable("not all value witnesses covered");
}



/// Find a witness to the fact that a type is a value type.
/// Always adds an i8*.
static void addValueWitness(IRGenModule &IGM, ConstantStructBuilder &B,
                            ValueWitness index, FixedPacking packing,
                            CanType abstractType, SILType concreteType,
                            const TypeInfo &concreteTI,
                            const std::optional<BoundGenericTypeCharacteristics>
                                boundGenericCharacteristics = std::nullopt) {
  auto addFunction = [&](llvm::Constant *fn) {
    fn = llvm::ConstantExpr::getBitCast(fn, IGM.Int8PtrTy);
    B.addSignedPointer(fn, IGM.getOptions().PointerAuth.ValueWitnesses, index);
  };

  // Copyable and noncopyable types share a value witness table layout. It
  // should normally be statically impossible to generate a call to a copy
  // value witness, but if somebody manages to dynamically get hold of metadata
  // for a noncopyable type, and tries to use it to copy values of that type,
  // we should trap to prevent the attempt.
  if (!concreteTI.isCopyable(ResilienceExpansion::Maximal)
      && valueWitnessRequiresCopyability(index)) {
    return addFunction(getNoncopyableTrapFunction(IGM));
  }

  // Try to use a standard function.
  switch (index) {
  case ValueWitness::Destroy:
    if (concreteTI.isTriviallyDestroyable(ResilienceExpansion::Maximal)) {
      return addFunction(getNoOpVoidFunction(IGM));
    } else if (concreteTI.isSingleSwiftRetainablePointer(ResilienceExpansion::Maximal)) {
      return addFunction(getDestroyStrongFunction(IGM));
    } else if (layoutStringsEnabled(IGM)) {
      auto ty = boundGenericCharacteristics ? boundGenericCharacteristics->concreteType : concreteType;
      auto &typeInfo = boundGenericCharacteristics ? *boundGenericCharacteristics->TI : concreteTI;
      if (auto *typeLayoutEntry =
            typeInfo.buildTypeLayoutEntry(IGM, ty, /*useStructLayouts*/true)) {
        auto genericSig = concreteType.getNominalOrBoundGenericNominal()
                              ->getGenericSignature();
        if (typeLayoutEntry->layoutString(IGM, genericSig) ||
            isRuntimeInstatiatedLayoutString(IGM, typeLayoutEntry)) {
          return addFunction(IGM.getGenericDestroyFn());
        }
      }
    }
    goto standard;

  case ValueWitness::InitializeBufferWithCopyOfBuffer:
    if (packing == FixedPacking::OffsetZero) {
      if (concreteTI.isTriviallyDestroyable(ResilienceExpansion::Maximal)) {
        return addFunction(getMemCpyFunction(IGM, concreteTI));
      } else if (concreteTI.isSingleSwiftRetainablePointer(ResilienceExpansion::Maximal)) {
        return addFunction(getInitWithCopyStrongFunction(IGM));
      }
    }

    if (layoutStringsEnabled(IGM)) {
      auto ty = boundGenericCharacteristics
                    ? boundGenericCharacteristics->concreteType
                    : concreteType;
      auto &typeInfo = boundGenericCharacteristics
                           ? *boundGenericCharacteristics->TI
                           : concreteTI;
      if (auto *typeLayoutEntry = typeInfo.buildTypeLayoutEntry(
              IGM, ty, /*useStructLayouts*/ true)) {
        auto genericSig = concreteType.getNominalOrBoundGenericNominal()
                              ->getGenericSignature();
        if (typeLayoutEntry->layoutString(IGM, genericSig) ||
            isRuntimeInstatiatedLayoutString(IGM, typeLayoutEntry)) {
          return addFunction(
              IGM.getGenericInitializeBufferWithCopyOfBufferFn());
        }
      }
    }
    goto standard;

  case ValueWitness::InitializeWithTake:
    if (concreteTI.isBitwiseTakable(ResilienceExpansion::Maximal)) {
      return addFunction(getMemCpyFunction(IGM, concreteTI));
    } else if (layoutStringsEnabled(IGM)) {
      auto ty = boundGenericCharacteristics ? boundGenericCharacteristics->concreteType : concreteType;
      auto &typeInfo = boundGenericCharacteristics ? *boundGenericCharacteristics->TI : concreteTI;
      if (auto *typeLayoutEntry =
            typeInfo.buildTypeLayoutEntry(IGM, ty, /*useStructLayouts*/true)) {
        auto genericSig = concreteType.getNominalOrBoundGenericNominal()
                              ->getGenericSignature();
        if (typeLayoutEntry->layoutString(IGM, genericSig) ||
            isRuntimeInstatiatedLayoutString(IGM, typeLayoutEntry)) {
          return addFunction(IGM.getGenericInitWithTakeFn());
        }
      }
    }
    goto standard;

  case ValueWitness::AssignWithCopy:
    if (concreteTI.isTriviallyDestroyable(ResilienceExpansion::Maximal)) {
      return addFunction(getMemCpyFunction(IGM, concreteTI));
    } else if (concreteTI.isSingleSwiftRetainablePointer(ResilienceExpansion::Maximal)) {
      return addFunction(getAssignWithCopyStrongFunction(IGM));
    } else if (layoutStringsEnabled(IGM)) {
      auto ty = boundGenericCharacteristics ? boundGenericCharacteristics->concreteType : concreteType;
      auto &typeInfo = boundGenericCharacteristics ? *boundGenericCharacteristics->TI : concreteTI;
      if (auto *typeLayoutEntry =
            typeInfo.buildTypeLayoutEntry(IGM, ty, /*useStructLayouts*/true)) {
        auto genericSig = concreteType.getNominalOrBoundGenericNominal()
                              ->getGenericSignature();
        if (typeLayoutEntry->layoutString(IGM, genericSig) ||
            isRuntimeInstatiatedLayoutString(IGM, typeLayoutEntry)) {
          return addFunction(IGM.getGenericAssignWithCopyFn());
        }
      }
    }
    goto standard;

  case ValueWitness::AssignWithTake:
    if (concreteTI.isTriviallyDestroyable(ResilienceExpansion::Maximal)) {
      return addFunction(getMemCpyFunction(IGM, concreteTI));
    } else if (concreteTI.isSingleSwiftRetainablePointer(ResilienceExpansion::Maximal)) {
      return addFunction(getAssignWithTakeStrongFunction(IGM));
    } else if (layoutStringsEnabled(IGM)) {
      auto ty = boundGenericCharacteristics ? boundGenericCharacteristics->concreteType : concreteType;
      auto &typeInfo = boundGenericCharacteristics ? *boundGenericCharacteristics->TI : concreteTI;
      if (auto *typeLayoutEntry =
            typeInfo.buildTypeLayoutEntry(IGM, ty, /*useStructLayouts*/true)) {
        auto genericSig = concreteType.getNominalOrBoundGenericNominal()
                              ->getGenericSignature();
        if (typeLayoutEntry->layoutString(IGM, genericSig) ||
            isRuntimeInstatiatedLayoutString(IGM, typeLayoutEntry)) {
          return addFunction(IGM.getGenericAssignWithTakeFn());
        }
      }
    }
    goto standard;

  case ValueWitness::InitializeWithCopy:
    if (concreteTI.isTriviallyDestroyable(ResilienceExpansion::Maximal)) {
      return addFunction(getMemCpyFunction(IGM, concreteTI));
    } else if (concreteTI.isSingleSwiftRetainablePointer(ResilienceExpansion::Maximal)) {
      return addFunction(getInitWithCopyStrongFunction(IGM));
    } else if (layoutStringsEnabled(IGM)) {
      auto ty = boundGenericCharacteristics ? boundGenericCharacteristics->concreteType : concreteType;
      auto &typeInfo = boundGenericCharacteristics ? *boundGenericCharacteristics->TI : concreteTI;
      if (auto *typeLayoutEntry =
            typeInfo.buildTypeLayoutEntry(IGM, ty, /*useStructLayouts*/true)) {
        auto genericSig = concreteType.getNominalOrBoundGenericNominal()
                              ->getGenericSignature();
        if (typeLayoutEntry->layoutString(IGM, genericSig) ||
            isRuntimeInstatiatedLayoutString(IGM, typeLayoutEntry)) {
          return addFunction(IGM.getGenericInitWithCopyFn());
        }
      }
    }
    goto standard;

  case ValueWitness::Size: {
    if (boundGenericCharacteristics)
      return addSize(B, boundGenericCharacteristics->TI, IGM);
    return addSize(B, &concreteTI, IGM);
  }

  case ValueWitness::Flags: {
    if (boundGenericCharacteristics)
      return B.addInt32(
          getValueWitnessFlags(boundGenericCharacteristics->TI,
                               boundGenericCharacteristics->concreteType,
                               boundGenericCharacteristics->packing)
              .getOpaqueValue());
    return B.addInt32(getValueWitnessFlags(&concreteTI, concreteType, packing)
                          .getOpaqueValue());
  }

  case ValueWitness::ExtraInhabitantCount: {
    if (boundGenericCharacteristics)
      return B.addInt32(
          getExtraInhabitantCount(boundGenericCharacteristics->TI, IGM));
    return B.addInt32(getExtraInhabitantCount(&concreteTI, IGM));
  }

  case ValueWitness::Stride: {
    if (boundGenericCharacteristics)
      return addStride(B, boundGenericCharacteristics->TI, IGM);
    return addStride(B, &concreteTI, IGM);
  }

  case ValueWitness::GetEnumTagSinglePayload: {
    if (boundGenericCharacteristics)
      if (auto *enumDecl = boundGenericCharacteristics->concreteType
                               .getEnumOrBoundGenericEnum())
        if (IGM.getMetadataLayout(enumDecl).hasPayloadSizeOffset())
          return B.add(llvm::ConstantExpr::getBitCast(
              IGM.getGetMultiPayloadEnumTagSinglePayloadFn(), IGM.Int8PtrTy));
    goto standard;
  }
  case ValueWitness::StoreEnumTagSinglePayload: {
    if (boundGenericCharacteristics)
      if (auto *enumDecl = boundGenericCharacteristics->concreteType
                               .getEnumOrBoundGenericEnum())
        if (IGM.getMetadataLayout(enumDecl).hasPayloadSizeOffset())
          return B.add(llvm::ConstantExpr::getBitCast(
              IGM.getStoreMultiPayloadEnumTagSinglePayloadFn(), IGM.Int8PtrTy));
    goto standard;
  }

  case ValueWitness::GetEnumTag: {
    assert(concreteType.getEnumOrBoundGenericEnum());

    if (layoutStringsEnabled(IGM)) {
      auto ty = boundGenericCharacteristics
                    ? boundGenericCharacteristics->concreteType
                    : concreteType;
      auto &typeInfo = boundGenericCharacteristics
                           ? *boundGenericCharacteristics->TI
                           : concreteTI;
      if (auto *typeLayoutEntry = typeInfo.buildTypeLayoutEntry(
              IGM, ty, /*useStructLayouts*/ true)) {
        if (auto *enumLayoutEntry = typeLayoutEntry->getAsEnum()) {
          auto genericSig = concreteType.getNominalOrBoundGenericNominal()
                              ->getGenericSignature();
          if (auto *fn = getEnumTagFunction(IGM, enumLayoutEntry, genericSig)) {
            return addFunction(fn);
          }
        }
      }
    }
    goto standard;
  }
  case ValueWitness::DestructiveInjectEnumTag: {
    assert(concreteType.getEnumOrBoundGenericEnum());
    if (layoutStringsEnabled(IGM)) {
      auto ty = boundGenericCharacteristics
                    ? boundGenericCharacteristics->concreteType
                    : concreteType;
      auto &typeInfo = boundGenericCharacteristics
                           ? *boundGenericCharacteristics->TI
                           : concreteTI;
      if (auto *typeLayoutEntry = typeInfo.buildTypeLayoutEntry(
              IGM, ty, /*useStructLayouts*/ true)) {
        if (auto *enumLayoutEntry = typeLayoutEntry->getAsEnum()) {
          auto genericSig = concreteType.getNominalOrBoundGenericNominal()
                                ->getGenericSignature();
          if (auto *fn = getDestructiveInjectEnumTagFunction(
                  IGM, enumLayoutEntry, genericSig)) {
            return addFunction(fn);
          }
        }
      }
    }
    goto standard;
  }
  case ValueWitness::DestructiveProjectEnumData:
    assert(concreteType.getEnumOrBoundGenericEnum());
    goto standard;
  }
  llvm_unreachable("bad value witness kind");

 standard:
  llvm::Function *fn = IGM.getOrCreateValueWitnessFunction(
      index, packing, abstractType, concreteType, concreteTI);
  addFunction(fn);
 }

 llvm::Function *IRGenModule::getOrCreateValueWitnessFunction(
     ValueWitness index, FixedPacking packing, CanType abstractType,
     SILType concreteType, const TypeInfo &type) {
  llvm::Function *fn =
      getAddrOfValueWitness(abstractType, index, ForDefinition);
  if (fn->empty())
  buildValueWitnessFunction(*this, fn, index, packing, abstractType,
                            concreteType, type);
  return fn;
 }

static bool shouldAddEnumWitnesses(CanType abstractType) {
  // Needs to handle UnboundGenericType.
  return dyn_cast_or_null<EnumDecl>(abstractType.getAnyNominal()) != nullptr;
}

static llvm::StructType *getValueWitnessTableType(IRGenModule &IGM,
                                                  CanType abstractType) {
  return shouldAddEnumWitnesses(abstractType)
           ? IGM.getEnumValueWitnessTableTy()
           : IGM.getValueWitnessTableTy();
}

/// Collect the value witnesses for a particular type.
static void
addValueWitnesses(IRGenModule &IGM, ConstantStructBuilder &B,
                  FixedPacking packing, CanType abstractType,
                  SILType concreteType, const TypeInfo &concreteTI,
                  const std::optional<BoundGenericTypeCharacteristics>
                      boundGenericCharacteristics = std::nullopt) {
  for (unsigned i = 0; i != NumRequiredValueWitnesses; ++i) {
    addValueWitness(IGM, B, ValueWitness(i), packing, abstractType,
                    concreteType, concreteTI, boundGenericCharacteristics);
  }
  if (shouldAddEnumWitnesses(abstractType)) {
    for (auto i = unsigned(ValueWitness::First_EnumValueWitness);
         i <= unsigned(ValueWitness::Last_EnumValueWitness);
         ++i) {
      addValueWitness(IGM, B, ValueWitness(i), packing, abstractType,
                      concreteType, concreteTI, boundGenericCharacteristics);
    }
  }
}

/// True if a type has a generic-parameter-dependent value witness table.
/// Currently, this is true if the size and/or alignment of the type is
/// dependent on its generic parameters.
bool irgen::hasDependentValueWitnessTable(IRGenModule &IGM, NominalTypeDecl *decl) {
  auto ty = decl->mapTypeIntoContext(decl->getDeclaredInterfaceType());
  return !IGM.getTypeInfoForUnlowered(ty).isFixedSize();
}

static void addValueWitnessesForAbstractType(IRGenModule &IGM,
                                             ConstantStructBuilder &B,
                                             CanType abstractType,
                                             bool &canBeConstant) {
  std::optional<BoundGenericTypeCharacteristics> boundGenericCharacteristics;
  if (auto boundGenericType = dyn_cast<BoundGenericType>(abstractType)) {
    CanType concreteFormalType = getFormalTypeInPrimaryContext(abstractType);

    auto concreteLoweredType = IGM.getLoweredType(concreteFormalType);
    const auto *boundConcreteTI = &IGM.getTypeInfo(concreteLoweredType);
    auto packing = boundConcreteTI->getFixedPacking(IGM);
    boundGenericCharacteristics = {concreteLoweredType, boundConcreteTI,
                                   packing};

    abstractType =
        boundGenericType->getDecl()->getDeclaredType()->getCanonicalType();
  }
  CanType concreteFormalType = getFormalTypeInPrimaryContext(abstractType);

  auto concreteLoweredType = IGM.getLoweredType(concreteFormalType);
  auto &concreteTI = IGM.getTypeInfo(concreteLoweredType);
  FixedPacking packing = concreteTI.getFixedPacking(IGM);

  // For now, assume that we never have any interest in dynamically
  // changing the value witnesses for something that's fixed-layout.
  canBeConstant = boundGenericCharacteristics
                      ? boundGenericCharacteristics->TI->isFixedSize()
                      : concreteTI.isFixedSize();

  addValueWitnesses(IGM, B, packing, abstractType, concreteLoweredType,
                    concreteTI, boundGenericCharacteristics);
}

static constexpr uint64_t sizeAndAlignment(Size size, Alignment alignment) {
  return ((uint64_t)size.getValue() << 32) | alignment.getValue();
}

/// Return a reference to a known value witness table from the runtime
/// that's suitable for the given type, if there is one, or return null
/// if we should emit a new one.
static ConstantReference
getAddrOfKnownValueWitnessTable(IRGenModule &IGM, CanType type,
                                bool relativeReference) {
  // Native PE binaries shouldn't reference data symbols across DLLs, so disable
  // this on Windows, unless we're forming a relative indirectable reference.
  if (IGM.useDllStorage() && !relativeReference)
    return {};
  
  if (auto nom = type->getAnyNominal()) {
    // TODO: Non-C enums have extra inhabitants and also need additional value
    // witnesses for their tag manipulation (except when they're empty, in
    // which case values never exist to witness).
    if (auto enumDecl = dyn_cast<EnumDecl>(nom))
      if (!enumDecl->isObjC() && !type->isUninhabited())
        return {};
  }
 
  auto &C = IGM.Context;

  type = getFormalTypeInPrimaryContext(type);
  
  auto &ti = IGM.getTypeInfoForUnlowered(AbstractionPattern::getOpaque(), type);

    // We only have known value witness tables for copyable types currently.
  if (!ti.isCopyable(ResilienceExpansion::Maximal)) {
    return {};
  }
  
  // We only have witnesses for fixed type info.
  auto *fixedTI = dyn_cast<FixedTypeInfo>(&ti);
  if (!fixedTI)
    return {};

  CanType witnessSurrogate;
  ReferenceCounting refCounting;

  // Empty types can use empty tuple witnesses.
  if (ti.isKnownEmpty(ResilienceExpansion::Maximal)) {
    witnessSurrogate = TupleType::getEmpty(C);
  // Handle common POD type layouts.
  } else if (fixedTI->isTriviallyDestroyable(ResilienceExpansion::Maximal)
      && fixedTI->getFixedExtraInhabitantCount(IGM) == 0) {
    // Reuse one of the integer witnesses if applicable.
    switch (sizeAndAlignment(fixedTI->getFixedSize(),
                             fixedTI->getFixedAlignment())) {
    case sizeAndAlignment(Size(0), Alignment::create<1>()):
      witnessSurrogate = TupleType::getEmpty(C);
      break;
    case sizeAndAlignment(Size(1), Alignment::create<1>()):
      witnessSurrogate = BuiltinIntegerType::get(8, C)->getCanonicalType();
      break;
    case sizeAndAlignment(Size(2), Alignment::create<2>()):
      witnessSurrogate = BuiltinIntegerType::get(16, C)->getCanonicalType();
      break;
    case sizeAndAlignment(Size(4), Alignment::create<4>()):
      witnessSurrogate = BuiltinIntegerType::get(32, C)->getCanonicalType();
      break;
    case sizeAndAlignment(Size(8), Alignment::create<8>()):
      witnessSurrogate = BuiltinIntegerType::get(64, C)->getCanonicalType();
      break;
    case sizeAndAlignment(Size(16), Alignment::create<16>()):
      witnessSurrogate = BuiltinIntegerType::get(128, C)->getCanonicalType();
      break;
    case sizeAndAlignment(Size(32), Alignment::create<32>()):
      witnessSurrogate = BuiltinIntegerType::get(256, C)->getCanonicalType();
      break;
    case sizeAndAlignment(Size(64), Alignment::create<64>()):
      witnessSurrogate = BuiltinIntegerType::get(512, C)->getCanonicalType();
      break;
    }
  } else if (fixedTI->isSingleRetainablePointer(ResilienceExpansion::Maximal,
                                                &refCounting)) {
    switch (refCounting) {
    case ReferenceCounting::Native:
      witnessSurrogate = C.TheNativeObjectType;
      break;
    case ReferenceCounting::ObjC:
    case ReferenceCounting::Block:
    case ReferenceCounting::Unknown:
      witnessSurrogate = C.getAnyObjectType();
      break;
    case ReferenceCounting::Bridge:
      witnessSurrogate = C.TheBridgeObjectType;
      break;
    case ReferenceCounting::Error:
    case ReferenceCounting::None:
    case ReferenceCounting::Custom:
      break;
    }
  }

  if (witnessSurrogate) {
    if (relativeReference) {
      return IGM.getAddrOfLLVMVariableOrGOTEquivalent(
                            LinkEntity::forValueWitnessTable(witnessSurrogate));
    } else {
      return {IGM.getAddrOfValueWitnessTable(witnessSurrogate),
              ConstantReference::Direct};
    }
  }
  return {};
}

llvm::Constant *
IRGenModule::getAddrOfEffectiveValueWitnessTable(CanType concreteType,
                                                 ConstantInit init) {
  if (auto known =
          getAddrOfKnownValueWitnessTable(*this, concreteType, false)) {
    return known.getValue();
  }
  return getAddrOfValueWitnessTable(concreteType);
}

/// Emit a value-witness table for the given type.
ConstantReference irgen::emitValueWitnessTable(IRGenModule &IGM,
                                             CanType abstractType,
                                             bool isPattern,
                                             bool relativeReference) {
  // See if we can use a prefab witness table from the runtime.
  if (!isPattern) {
    if (auto known = getAddrOfKnownValueWitnessTable(IGM, abstractType,
                                                     relativeReference)) {
      return known;
    }
  }
  
  // We should never be making a pattern if the layout isn't fixed.
  // The reverse can be true for types whose layout depends on
  // resilient types.
  assert((!isPattern || hasDependentValueWitnessTable(
              IGM, abstractType->getAnyNominal())) &&
         "emitting VWT pattern for fixed-layout type");

  ConstantInitBuilder builder(IGM);
  auto witnesses =
    builder.beginStruct(getValueWitnessTableType(IGM, abstractType));

  bool canBeConstant = false;
  addValueWitnessesForAbstractType(IGM, witnesses, abstractType, canBeConstant);

  // If this is just an instantiation pattern, we should never be modifying
  // it in-place.
  if (isPattern) canBeConstant = true;

  auto addr = IGM.getAddrOfValueWitnessTable(abstractType,
                                             witnesses.finishAndCreateFuture());
  auto global = cast<llvm::GlobalVariable>(addr);
  global->setConstant(canBeConstant);

  return {llvm::ConstantExpr::getBitCast(global, IGM.WitnessTablePtrTy),
          ConstantReference::Direct};
}

llvm::Constant *IRGenModule::emitFixedTypeLayout(CanType t,
                                                 const FixedTypeInfo &ti) {
  auto silTy = SILType::getPrimitiveAddressType(t);
  // Collect the interesting information that gets encoded in a type layout
  // record, to see if there's one we can reuse.
  unsigned size = ti.getFixedSize().getValue();
  unsigned align = ti.getFixedAlignment().getValue();

  bool pod = ti.isTriviallyDestroyable(ResilienceExpansion::Maximal);
  IsBitwiseTakable_t bt = ti.getBitwiseTakable(ResilienceExpansion::Maximal);
  unsigned numExtraInhabitants = ti.getFixedExtraInhabitantCount(*this);

  // Try to use common type layouts exported by the runtime.
  llvm::Constant *commonValueWitnessTable = nullptr;
  if (pod && bt == IsBitwiseTakableAndBorrowable && numExtraInhabitants == 0) {
    if (size == 0)
      commonValueWitnessTable =
        getAddrOfValueWitnessTable(Context.TheEmptyTupleType);
    if (   (size ==  1 && align ==  1)
        || (size ==  2 && align ==  2)
        || (size ==  4 && align ==  4)
        || (size ==  8 && align ==  8)
        || (size == 16 && align == 16)
        || (size == 32 && align == 32))
      commonValueWitnessTable =
        getAddrOfValueWitnessTable(BuiltinIntegerType::get(size * 8, Context)
                                     ->getCanonicalType());
  }

  if (commonValueWitnessTable) {
    auto index = llvm::ConstantInt::get(Int32Ty,
                               (unsigned)ValueWitness::First_TypeLayoutWitness);
    return llvm::ConstantExpr::getGetElementPtr(Int8PtrTy,
                                                commonValueWitnessTable,
                                                index);
  }

  // Otherwise, see if a layout has been emitted with these characteristics
  // already.
  FixedLayoutKey key{size, numExtraInhabitants, align, pod, unsigned(bt)};

  auto found = PrivateFixedLayouts.find(key);
  if (found != PrivateFixedLayouts.end())
    return found->second;

  // Emit the layout values.
  ConstantInitBuilder builder(*this);
  auto witnesses = builder.beginStruct();
  FixedPacking packing = ti.getFixedPacking(*this);
  for (auto witness = ValueWitness::First_TypeLayoutWitness;
       witness <= ValueWitness::Last_RequiredTypeLayoutWitness;
       witness = ValueWitness(unsigned(witness) + 1)) {
    addValueWitness(*this, witnesses, witness, packing, t, silTy, ti);
  }

  auto pod_bt_string = [](bool pod, IsBitwiseTakable_t bt) -> StringRef {
    if (pod) {
      return "_pod";
    }
    switch (bt) {
    case IsNotBitwiseTakable:
      return "";
    case IsBitwiseTakableOnly:
      return "_bt_nbb";
    case IsBitwiseTakableAndBorrowable:
      return "_bt";
    }
  };

  auto layoutVar
    = witnesses.finishAndCreateGlobal(
        "type_layout_" + llvm::Twine(size)
                       + "_" + llvm::Twine(align)
                       + "_" + llvm::Twine::utohexstr(numExtraInhabitants)
                       + pod_bt_string(pod, bt),
        getPointerAlignment(),
        /*constant*/ true,
        llvm::GlobalValue::PrivateLinkage);

  // Cast to the standard currency type for type layouts.
  auto layout = llvm::ConstantExpr::getBitCast(layoutVar, Int8PtrPtrTy);

  PrivateFixedLayouts.insert({key, layout});
  return layout;
}

FixedPacking TypeInfo::getFixedPacking(IRGenModule &IGM) const {
  auto fixedTI = dyn_cast<FixedTypeInfo>(this);

  // If the type isn't fixed, we have to do something dynamic.
  // FIXME: some types are provably too big (or aligned) to be
  // allocated inline.
  if (!fixedTI)
    return FixedPacking::Dynamic;

  // By convention we only store bitwise takable values inline.
  if (!fixedTI->isBitwiseTakable(ResilienceExpansion::Maximal))
    return FixedPacking::Allocate;

  Size bufferSize = getFixedBufferSize(IGM);
  Size requiredSize = fixedTI->getFixedSize();

  // Flat out, if we need more space than the buffer provides,
  // we always have to allocate.
  // FIXME: there might be some interesting cases where this
  // is suboptimal for enums.
  if (requiredSize > bufferSize)
    return FixedPacking::Allocate;

  Alignment bufferAlign = getFixedBufferAlignment(IGM);
  Alignment requiredAlign = fixedTI->getFixedAlignment();

  // If the buffer alignment is good enough for the type, great.
  if (bufferAlign >= requiredAlign)
    return FixedPacking::OffsetZero;

  // TODO: consider using a slower mode that dynamically checks
  // whether the buffer size is small enough.

  // Otherwise we're stuck and have to separately allocate.
  return FixedPacking::Allocate;
}

bool TypeInfo::canValueWitnessExtraInhabitantsUpTo(IRGenModule &IGM,
                                                   unsigned index) const {
  // If this type is POD, then its value witnesses are trivial, so can handle
  // any bit pattern.
  if (isTriviallyDestroyable(ResilienceExpansion::Maximal)) {
    return true;
  }
  
  // By default, assume that extra inhabitants must be branched out on.
  return false;
}

Address TypeInfo::indexArray(IRGenFunction &IGF, Address base,
                             llvm::Value *index, SILType T) const {
  // The stride of a Swift type may not match its LLVM size. If we know we have
  // a fixed stride different from our size, or we have a dynamic size,
  // do a byte-level GEP with the proper stride.
  const auto *fixedTI = dyn_cast<FixedTypeInfo>(this);

  llvm::Value *destValue = nullptr;
  Size stride(1);
  
  // TODO: Arrays currently lower-bound the stride to 1.
  if (!fixedTI || fixedTI->getFixedStride() != fixedTI->getFixedSize()) {
    llvm::Value *byteAddr = IGF.Builder.CreateBitCast(base.getAddress(),
                                                      IGF.IGM.Int8PtrTy);
    llvm::Value *size = getStride(IGF, T);
    if (size->getType() != index->getType())
      size = IGF.Builder.CreateZExtOrTrunc(size, index->getType());
    llvm::Value *distance = IGF.Builder.CreateNSWMul(index, size);
    destValue =
        IGF.Builder.CreateInBoundsGEP(IGF.IGM.Int8Ty, byteAddr, distance);
    destValue = IGF.Builder.CreateBitCast(destValue, base.getType());
  } else {
    // We don't expose a non-inbounds GEP operation.
    destValue = IGF.Builder.CreateInBoundsGEP(getStorageType(),
                                              base.getAddress(), index);
    stride = fixedTI->getFixedStride();
  }
  if (auto *IndexConst = dyn_cast<llvm::ConstantInt>(index)) {
    // If we know the indexing value, we can get a better guess on the
    // alignment.
    // This even works if the stride is not known (and assumed to be 1).
    stride *= IndexConst->getValue().getZExtValue();
  }
  Alignment Align = base.getAlignment().alignmentAtOffset(stride);
  return Address(destValue, getStorageType(), Align);
}

Address TypeInfo::roundUpToTypeAlignment(IRGenFunction &IGF, Address base,
                                         SILType T) const {
  Alignment Align = base.getAlignment();
  llvm::Value *TyAlignMask = getAlignmentMask(IGF, T);
  if (auto *TyAlignMaskConst = dyn_cast<llvm::ConstantInt>(TyAlignMask)) {
    Alignment TyAlign(TyAlignMaskConst->getZExtValue() + 1);

    // No need to align if the base is already aligned.
    if (TyAlign <= Align)
      return base;
  }
  llvm::Value *Addr = base.getAddress();
  Addr = IGF.Builder.CreatePtrToInt(Addr, IGF.IGM.IntPtrTy);
  Addr = IGF.Builder.CreateNUWAdd(Addr, TyAlignMask);
  llvm::Value *InvertedMask = IGF.Builder.CreateNot(TyAlignMask);
  Addr = IGF.Builder.CreateAnd(Addr, InvertedMask);
  Addr = IGF.Builder.CreateIntToPtr(Addr, getStorageType()->getPointerTo());
  return Address(Addr, getStorageType(), Align);
}

void TypeInfo::destroyArray(IRGenFunction &IGF, Address array,
                            llvm::Value *count, SILType T) const {
  if (isTriviallyDestroyable(ResilienceExpansion::Maximal))
    return;

 emitDestroyArrayCall(IGF, T, array, count);
}

void TypeInfo::initializeArrayWithCopy(IRGenFunction &IGF,
                                       Address dest, Address src,
                                       llvm::Value *count, SILType T) const {
  if (isTriviallyDestroyable(ResilienceExpansion::Maximal)) {
    llvm::Value *stride = getStride(IGF, T);
    llvm::Value *byteCount = IGF.Builder.CreateNUWMul(stride, count);
    IGF.Builder.CreateMemCpy(
        dest.getAddress(), llvm::MaybeAlign(dest.getAlignment().getValue()),
        src.getAddress(), llvm::MaybeAlign(src.getAlignment().getValue()),
        byteCount);
    return;
  }

  emitInitializeArrayWithCopyCall(IGF, T, dest, src, count);
}

void TypeInfo::initializeArrayWithTakeNoAlias(IRGenFunction &IGF, Address dest,
                                              Address src, llvm::Value *count,
                                              SILType T) const {
  if (isBitwiseTakable(ResilienceExpansion::Maximal)) {
    llvm::Value *stride = getStride(IGF, T);
    llvm::Value *byteCount = IGF.Builder.CreateNUWMul(stride, count);
    IGF.Builder.CreateMemCpy(
        dest.getAddress(), llvm::MaybeAlign(dest.getAlignment().getValue()),
        src.getAddress(), llvm::MaybeAlign(src.getAlignment().getValue()),
        byteCount);
    return;
  }

  emitInitializeArrayWithTakeNoAliasCall(IGF, T, dest, src, count);
}

void TypeInfo::initializeArrayWithTakeFrontToBack(IRGenFunction &IGF,
                                                  Address dest, Address src,
                                                  llvm::Value *count, SILType T)
const {
  if (isBitwiseTakable(ResilienceExpansion::Maximal)) {
    llvm::Value *stride = getStride(IGF, T);
    llvm::Value *byteCount = IGF.Builder.CreateNUWMul(stride, count);
    IGF.Builder.CreateMemMove(
        dest.getAddress(), llvm::MaybeAlign(dest.getAlignment().getValue()),
        src.getAddress(), llvm::MaybeAlign(src.getAlignment().getValue()),
        byteCount);
    return;
  }

  emitInitializeArrayWithTakeFrontToBackCall(IGF, T, dest, src, count);
}

void TypeInfo::initializeArrayWithTakeBackToFront(IRGenFunction &IGF,
                                                  Address dest, Address src,
                                                  llvm::Value *count, SILType T)
const {
  if (isBitwiseTakable(ResilienceExpansion::Maximal)) {
    llvm::Value *stride = getStride(IGF, T);
    llvm::Value *byteCount = IGF.Builder.CreateNUWMul(stride, count);
    IGF.Builder.CreateMemMove(
        dest.getAddress(), llvm::MaybeAlign(dest.getAlignment().getValue()),
        src.getAddress(), llvm::MaybeAlign(src.getAlignment().getValue()),
        byteCount);
    return;
  }

  emitInitializeArrayWithTakeBackToFrontCall(IGF, T, dest, src, count);
}

void TypeInfo::assignArrayWithCopyNoAlias(IRGenFunction &IGF, Address dest,
                                          Address src, llvm::Value *count,
                                          SILType T) const {
  if (isTriviallyDestroyable(ResilienceExpansion::Maximal)) {
    llvm::Value *stride = getStride(IGF, T);
    llvm::Value *byteCount = IGF.Builder.CreateNUWMul(stride, count);
    IGF.Builder.CreateMemCpy(
        dest.getAddress(), llvm::MaybeAlign(dest.getAlignment().getValue()),
        src.getAddress(), llvm::MaybeAlign(src.getAlignment().getValue()),
        byteCount);
    return;
  }

  emitAssignArrayWithCopyNoAliasCall(IGF, T, dest, src, count);
}

void TypeInfo::assignArrayWithCopyFrontToBack(IRGenFunction &IGF, Address dest,
                                              Address src, llvm::Value *count,
                                              SILType T) const {
  if (isTriviallyDestroyable(ResilienceExpansion::Maximal)) {
    llvm::Value *stride = getStride(IGF, T);
    llvm::Value *byteCount = IGF.Builder.CreateNUWMul(stride, count);
    IGF.Builder.CreateMemMove(
        dest.getAddress(), llvm::MaybeAlign(dest.getAlignment().getValue()),
        src.getAddress(), llvm::MaybeAlign(src.getAlignment().getValue()),
        byteCount);
    return;
  }

  emitAssignArrayWithCopyFrontToBackCall(IGF, T, dest, src, count);
}

void TypeInfo::assignArrayWithCopyBackToFront(IRGenFunction &IGF, Address dest,
                                              Address src, llvm::Value *count,
                                              SILType T) const {
  if (isTriviallyDestroyable(ResilienceExpansion::Maximal)) {
    llvm::Value *stride = getStride(IGF, T);
    llvm::Value *byteCount = IGF.Builder.CreateNUWMul(stride, count);
    IGF.Builder.CreateMemMove(
        dest.getAddress(), llvm::MaybeAlign(dest.getAlignment().getValue()),
        src.getAddress(), llvm::MaybeAlign(src.getAlignment().getValue()),
        byteCount);
    return;
  }

  emitAssignArrayWithCopyBackToFrontCall(IGF, T, dest, src, count);
}

void TypeInfo::assignArrayWithTake(IRGenFunction &IGF, Address dest,
                                              Address src, llvm::Value *count,
                                              SILType T) const {
  if (isTriviallyDestroyable(ResilienceExpansion::Maximal)) {
    llvm::Value *stride = getStride(IGF, T);
    llvm::Value *byteCount = IGF.Builder.CreateNUWMul(stride, count);
    IGF.Builder.CreateMemCpy(
        dest.getAddress(), llvm::MaybeAlign(dest.getAlignment().getValue()),
        src.getAddress(), llvm::MaybeAlign(src.getAlignment().getValue()),
        byteCount);
    return;
  }

  emitAssignArrayWithTakeCall(IGF, T, dest, src, count);
}

void TypeInfo::collectMetadataForOutlining(OutliningMetadataCollector &c,
                                           SILType T) const {
  auto canType = T.getASTType();
  assert(!canType->is<ArchetypeType>() && "Did not expect an ArchetypeType");
  (void)canType;
}