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
//! Confirmation.
//!
//! Confirmation unifies the output type parameters of the trait
//! with the values found in the obligation, possibly yielding a
//! type error. See the [rustc dev guide] for more details.
//!
//! [rustc dev guide]:
//! https://rustc-dev-guide.rust-lang.org/traits/resolution.html#confirmation
use rustc_ast::Mutability;
use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_hir::lang_items::LangItem;
use rustc_infer::infer::HigherRankedType;
use rustc_infer::infer::{DefineOpaqueTypes, InferOk};
use rustc_middle::traits::{BuiltinImplSource, SignatureMismatchData};
use rustc_middle::ty::{
    self, GenericArgs, GenericArgsRef, GenericParamDefKind, ToPolyTraitRef, ToPredicate,
    TraitPredicate, Ty, TyCtxt, TypeVisitableExt,
};
use rustc_span::def_id::DefId;

use crate::traits::normalize::{normalize_with_depth, normalize_with_depth_to};
use crate::traits::util::{self, closure_trait_ref_and_return_type};
use crate::traits::vtable::{
    count_own_vtable_entries, prepare_vtable_segments, vtable_trait_first_method_offset,
    VtblSegment,
};
use crate::traits::{
    BuiltinDerivedObligation, ImplDerivedObligation, ImplDerivedObligationCause, ImplSource,
    ImplSourceUserDefinedData, Normalized, Obligation, ObligationCause, PolyTraitObligation,
    PredicateObligation, Selection, SelectionError, SignatureMismatch, TraitNotObjectSafe,
    Unimplemented,
};

use super::BuiltinImplConditions;
use super::SelectionCandidate::{self, *};
use super::SelectionContext;

use std::iter;
use std::ops::ControlFlow;

impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
    #[instrument(level = "debug", skip(self))]
    pub(super) fn confirm_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
        candidate: SelectionCandidate<'tcx>,
    ) -> Result<Selection<'tcx>, SelectionError<'tcx>> {
        let mut impl_src = match candidate {
            BuiltinCandidate { has_nested } => {
                let data = self.confirm_builtin_candidate(obligation, has_nested);
                ImplSource::Builtin(BuiltinImplSource::Misc, data)
            }

            TransmutabilityCandidate => {
                let data = self.confirm_transmutability_candidate(obligation)?;
                ImplSource::Builtin(BuiltinImplSource::Misc, data)
            }

            ParamCandidate(param) => {
                let obligations =
                    self.confirm_param_candidate(obligation, param.map_bound(|t| t.trait_ref));
                ImplSource::Param(obligations)
            }

            ImplCandidate(impl_def_id) => {
                ImplSource::UserDefined(self.confirm_impl_candidate(obligation, impl_def_id))
            }

            AutoImplCandidate => {
                let data = self.confirm_auto_impl_candidate(obligation)?;
                ImplSource::Builtin(BuiltinImplSource::Misc, data)
            }

            ProjectionCandidate(idx) => {
                let obligations = self.confirm_projection_candidate(obligation, idx)?;
                ImplSource::Param(obligations)
            }

            ObjectCandidate(idx) => self.confirm_object_candidate(obligation, idx)?,

            ClosureCandidate { .. } => {
                let vtable_closure = self.confirm_closure_candidate(obligation)?;
                ImplSource::Builtin(BuiltinImplSource::Misc, vtable_closure)
            }

            AsyncClosureCandidate => {
                let vtable_closure = self.confirm_async_closure_candidate(obligation)?;
                ImplSource::Builtin(BuiltinImplSource::Misc, vtable_closure)
            }

            // No nested obligations or confirmation process. The checks that we do in
            // candidate assembly are sufficient.
            AsyncFnKindHelperCandidate => ImplSource::Builtin(BuiltinImplSource::Misc, vec![]),

            CoroutineCandidate => {
                let vtable_coroutine = self.confirm_coroutine_candidate(obligation)?;
                ImplSource::Builtin(BuiltinImplSource::Misc, vtable_coroutine)
            }

            FutureCandidate => {
                let vtable_future = self.confirm_future_candidate(obligation)?;
                ImplSource::Builtin(BuiltinImplSource::Misc, vtable_future)
            }

            IteratorCandidate => {
                let vtable_iterator = self.confirm_iterator_candidate(obligation)?;
                ImplSource::Builtin(BuiltinImplSource::Misc, vtable_iterator)
            }

            AsyncIteratorCandidate => {
                let vtable_iterator = self.confirm_async_iterator_candidate(obligation)?;
                ImplSource::Builtin(BuiltinImplSource::Misc, vtable_iterator)
            }

            FnPointerCandidate { fn_host_effect } => {
                let data = self.confirm_fn_pointer_candidate(obligation, fn_host_effect)?;
                ImplSource::Builtin(BuiltinImplSource::Misc, data)
            }

            TraitAliasCandidate => {
                let data = self.confirm_trait_alias_candidate(obligation);
                ImplSource::Builtin(BuiltinImplSource::Misc, data)
            }

            BuiltinObjectCandidate => {
                // This indicates something like `Trait + Send: Send`. In this case, we know that
                // this holds because that's what the object type is telling us, and there's really
                // no additional obligations to prove and no types in particular to unify, etc.
                ImplSource::Builtin(BuiltinImplSource::Misc, Vec::new())
            }

            BuiltinUnsizeCandidate => self.confirm_builtin_unsize_candidate(obligation)?,

            TraitUpcastingUnsizeCandidate(idx) => {
                self.confirm_trait_upcasting_unsize_candidate(obligation, idx)?
            }

            ConstDestructCandidate(def_id) => {
                let data = self.confirm_const_destruct_candidate(obligation, def_id)?;
                ImplSource::Builtin(BuiltinImplSource::Misc, data)
            }
        };

        // The obligations returned by confirmation are recursively evaluated
        // so we need to make sure they have the correct depth.
        for subobligation in impl_src.borrow_nested_obligations_mut() {
            subobligation.set_depth_from_parent(obligation.recursion_depth);
        }

        Ok(impl_src)
    }

    fn confirm_projection_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
        idx: usize,
    ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
        let tcx = self.tcx();

        let trait_predicate = self.infcx.shallow_resolve(obligation.predicate);
        let placeholder_trait_predicate =
            self.infcx.enter_forall_and_leak_universe(trait_predicate).trait_ref;
        let placeholder_self_ty = placeholder_trait_predicate.self_ty();
        let candidate_predicate = self
            .for_each_item_bound(
                placeholder_self_ty,
                |_, clause, clause_idx| {
                    if clause_idx == idx {
                        ControlFlow::Break(clause)
                    } else {
                        ControlFlow::Continue(())
                    }
                },
                || unreachable!(),
            )
            .break_value()
            .expect("expected to index into clause that exists");
        let candidate = candidate_predicate
            .as_trait_clause()
            .expect("projection candidate is not a trait predicate")
            .map_bound(|t| t.trait_ref);

        let candidate = self.infcx.instantiate_binder_with_fresh_vars(
            obligation.cause.span,
            HigherRankedType,
            candidate,
        );
        let mut obligations = Vec::new();
        let candidate = normalize_with_depth_to(
            self,
            obligation.param_env,
            obligation.cause.clone(),
            obligation.recursion_depth + 1,
            candidate,
            &mut obligations,
        );

        obligations.extend(
            self.infcx
                .at(&obligation.cause, obligation.param_env)
                .eq(DefineOpaqueTypes::No, placeholder_trait_predicate, candidate)
                .map(|InferOk { obligations, .. }| obligations)
                .map_err(|_| Unimplemented)?,
        );

        // FIXME(compiler-errors): I don't think this is needed.
        if let ty::Alias(ty::Projection, alias_ty) = placeholder_self_ty.kind() {
            let predicates = tcx.predicates_of(alias_ty.def_id).instantiate_own(tcx, alias_ty.args);
            for (predicate, _) in predicates {
                let normalized = normalize_with_depth_to(
                    self,
                    obligation.param_env,
                    obligation.cause.clone(),
                    obligation.recursion_depth + 1,
                    predicate,
                    &mut obligations,
                );
                obligations.push(Obligation::with_depth(
                    self.tcx(),
                    obligation.cause.clone(),
                    obligation.recursion_depth + 1,
                    obligation.param_env,
                    normalized,
                ));
            }
        }

        Ok(obligations)
    }

    fn confirm_param_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
        param: ty::PolyTraitRef<'tcx>,
    ) -> Vec<PredicateObligation<'tcx>> {
        debug!(?obligation, ?param, "confirm_param_candidate");

        // During evaluation, we already checked that this
        // where-clause trait-ref could be unified with the obligation
        // trait-ref. Repeat that unification now without any
        // transactional boundary; it should not fail.
        match self.match_where_clause_trait_ref(obligation, param) {
            Ok(obligations) => obligations,
            Err(()) => {
                bug!(
                    "Where clause `{:?}` was applicable to `{:?}` but now is not",
                    param,
                    obligation
                );
            }
        }
    }

    fn confirm_builtin_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
        has_nested: bool,
    ) -> Vec<PredicateObligation<'tcx>> {
        debug!(?obligation, ?has_nested, "confirm_builtin_candidate");

        let lang_items = self.tcx().lang_items();
        let obligations = if has_nested {
            let trait_def = obligation.predicate.def_id();
            let conditions = if Some(trait_def) == lang_items.sized_trait() {
                self.sized_conditions(obligation)
            } else if Some(trait_def) == lang_items.copy_trait() {
                self.copy_clone_conditions(obligation)
            } else if Some(trait_def) == lang_items.clone_trait() {
                self.copy_clone_conditions(obligation)
            } else {
                bug!("unexpected builtin trait {:?}", trait_def)
            };
            let BuiltinImplConditions::Where(nested) = conditions else {
                bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation);
            };

            let cause = obligation.derived_cause(BuiltinDerivedObligation);
            self.collect_predicates_for_types(
                obligation.param_env,
                cause,
                obligation.recursion_depth + 1,
                trait_def,
                nested,
            )
        } else {
            vec![]
        };

        debug!(?obligations);

        obligations
    }

    #[instrument(level = "debug", skip(self))]
    fn confirm_transmutability_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
    ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
        use rustc_transmute::{Answer, Condition};
        #[instrument(level = "debug", skip(tcx, obligation, predicate))]
        fn flatten_answer_tree<'tcx>(
            tcx: TyCtxt<'tcx>,
            obligation: &PolyTraitObligation<'tcx>,
            predicate: TraitPredicate<'tcx>,
            cond: Condition<rustc_transmute::layout::rustc::Ref<'tcx>>,
        ) -> Vec<PredicateObligation<'tcx>> {
            match cond {
                // FIXME(bryangarza): Add separate `IfAny` case, instead of treating as `IfAll`
                // Not possible until the trait solver supports disjunctions of obligations
                Condition::IfAll(conds) | Condition::IfAny(conds) => conds
                    .into_iter()
                    .flat_map(|cond| flatten_answer_tree(tcx, obligation, predicate, cond))
                    .collect(),
                Condition::IfTransmutable { src, dst } => {
                    let trait_def_id = obligation.predicate.def_id();
                    let assume_const = predicate.trait_ref.args.const_at(2);
                    let make_obl = |from_ty, to_ty| {
                        let trait_ref1 = ty::TraitRef::new(
                            tcx,
                            trait_def_id,
                            [
                                ty::GenericArg::from(to_ty),
                                ty::GenericArg::from(from_ty),
                                ty::GenericArg::from(assume_const),
                            ],
                        );
                        Obligation::with_depth(
                            tcx,
                            obligation.cause.clone(),
                            obligation.recursion_depth + 1,
                            obligation.param_env,
                            trait_ref1,
                        )
                    };

                    // If Dst is mutable, check bidirectionally.
                    // For example, transmuting bool -> u8 is OK as long as you can't update that u8
                    // to be > 1, because you could later transmute the u8 back to a bool and get UB.
                    match dst.mutability {
                        Mutability::Not => vec![make_obl(src.ty, dst.ty)],
                        Mutability::Mut => vec![make_obl(src.ty, dst.ty), make_obl(dst.ty, src.ty)],
                    }
                }
            }
        }

        // We erase regions here because transmutability calls layout queries,
        // which does not handle inference regions and doesn't particularly
        // care about other regions. Erasing late-bound regions is equivalent
        // to instantiating the binder with placeholders then erasing those
        // placeholder regions.
        let predicate = self
            .tcx()
            .erase_regions(self.tcx().instantiate_bound_regions_with_erased(obligation.predicate));

        let Some(assume) = rustc_transmute::Assume::from_const(
            self.infcx.tcx,
            obligation.param_env,
            predicate.trait_ref.args.const_at(2),
        ) else {
            return Err(Unimplemented);
        };

        let dst = predicate.trait_ref.args.type_at(0);
        let src = predicate.trait_ref.args.type_at(1);
        debug!(?src, ?dst);
        let mut transmute_env = rustc_transmute::TransmuteTypeEnv::new(self.infcx);
        let maybe_transmutable = transmute_env.is_transmutable(
            obligation.cause.clone(),
            rustc_transmute::Types { dst, src },
            assume,
        );

        let fully_flattened = match maybe_transmutable {
            Answer::No(_) => Err(Unimplemented)?,
            Answer::If(cond) => flatten_answer_tree(self.tcx(), obligation, predicate, cond),
            Answer::Yes => vec![],
        };

        debug!(?fully_flattened);
        Ok(fully_flattened)
    }

    /// This handles the case where an `auto trait Foo` impl is being used.
    /// The idea is that the impl applies to `X : Foo` if the following conditions are met:
    ///
    /// 1. For each constituent type `Y` in `X`, `Y : Foo` holds
    /// 2. For each where-clause `C` declared on `Foo`, `[Self => X] C` holds.
    fn confirm_auto_impl_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
    ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
        debug!(?obligation, "confirm_auto_impl_candidate");

        let self_ty = self.infcx.shallow_resolve(obligation.predicate.self_ty());
        let types = self.constituent_types_for_ty(self_ty)?;
        Ok(self.vtable_auto_impl(obligation, obligation.predicate.def_id(), types))
    }

    /// See `confirm_auto_impl_candidate`.
    fn vtable_auto_impl(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
        trait_def_id: DefId,
        nested: ty::Binder<'tcx, Vec<Ty<'tcx>>>,
    ) -> Vec<PredicateObligation<'tcx>> {
        debug!(?nested, "vtable_auto_impl");
        ensure_sufficient_stack(|| {
            let cause = obligation.derived_cause(BuiltinDerivedObligation);

            let poly_trait_ref = obligation.predicate.to_poly_trait_ref();
            let trait_ref = self.infcx.enter_forall_and_leak_universe(poly_trait_ref);
            let trait_obligations: Vec<PredicateObligation<'_>> = self.impl_or_trait_obligations(
                &cause,
                obligation.recursion_depth + 1,
                obligation.param_env,
                trait_def_id,
                trait_ref.args,
                obligation.predicate,
            );

            let mut obligations = self.collect_predicates_for_types(
                obligation.param_env,
                cause,
                obligation.recursion_depth + 1,
                trait_def_id,
                nested,
            );

            // Adds the predicates from the trait. Note that this contains a `Self: Trait`
            // predicate as usual. It won't have any effect since auto traits are coinductive.
            obligations.extend(trait_obligations);

            debug!(?obligations, "vtable_auto_impl");

            obligations
        })
    }

    fn confirm_impl_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
        impl_def_id: DefId,
    ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
        debug!(?obligation, ?impl_def_id, "confirm_impl_candidate");

        // First, create the generic parameters by matching the impl again,
        // this time not in a probe.
        let args = self.rematch_impl(impl_def_id, obligation);
        debug!(?args, "impl args");
        ensure_sufficient_stack(|| {
            self.vtable_impl(
                impl_def_id,
                args,
                &obligation.cause,
                obligation.recursion_depth + 1,
                obligation.param_env,
                obligation.predicate,
            )
        })
    }

    fn vtable_impl(
        &mut self,
        impl_def_id: DefId,
        args: Normalized<'tcx, GenericArgsRef<'tcx>>,
        cause: &ObligationCause<'tcx>,
        recursion_depth: usize,
        param_env: ty::ParamEnv<'tcx>,
        parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
    ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> {
        debug!(?impl_def_id, ?args, ?recursion_depth, "vtable_impl");

        let mut impl_obligations = self.impl_or_trait_obligations(
            cause,
            recursion_depth,
            param_env,
            impl_def_id,
            args.value,
            parent_trait_pred,
        );

        debug!(?impl_obligations, "vtable_impl");

        // Because of RFC447, the impl-trait-ref and obligations
        // are sufficient to determine the impl args, without
        // relying on projections in the impl-trait-ref.
        //
        // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V`
        impl_obligations.extend(args.obligations);

        ImplSourceUserDefinedData { impl_def_id, args: args.value, nested: impl_obligations }
    }

    fn confirm_object_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
        index: usize,
    ) -> Result<ImplSource<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
        let tcx = self.tcx();
        debug!(?obligation, ?index, "confirm_object_candidate");

        let trait_predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
        let self_ty = self.infcx.shallow_resolve(trait_predicate.self_ty());
        let ty::Dynamic(data, ..) = *self_ty.kind() else {
            span_bug!(obligation.cause.span, "object candidate with non-object");
        };

        let object_trait_ref = data.principal().unwrap_or_else(|| {
            span_bug!(obligation.cause.span, "object candidate with no principal")
        });
        let object_trait_ref = self.infcx.instantiate_binder_with_fresh_vars(
            obligation.cause.span,
            HigherRankedType,
            object_trait_ref,
        );
        let object_trait_ref = object_trait_ref.with_self_ty(self.tcx(), self_ty);

        let mut nested = vec![];

        let mut supertraits = util::supertraits(tcx, ty::Binder::dummy(object_trait_ref));
        let unnormalized_upcast_trait_ref =
            supertraits.nth(index).expect("supertraits iterator no longer has as many elements");

        let upcast_trait_ref = self.infcx.instantiate_binder_with_fresh_vars(
            obligation.cause.span,
            HigherRankedType,
            unnormalized_upcast_trait_ref,
        );
        let upcast_trait_ref = normalize_with_depth_to(
            self,
            obligation.param_env,
            obligation.cause.clone(),
            obligation.recursion_depth + 1,
            upcast_trait_ref,
            &mut nested,
        );

        nested.extend(
            self.infcx
                .at(&obligation.cause, obligation.param_env)
                .eq(DefineOpaqueTypes::No, trait_predicate.trait_ref, upcast_trait_ref)
                .map(|InferOk { obligations, .. }| obligations)
                .map_err(|_| Unimplemented)?,
        );

        // Check supertraits hold. This is so that their associated type bounds
        // will be checked in the code below.
        for super_trait in tcx
            .super_predicates_of(trait_predicate.def_id())
            .instantiate(tcx, trait_predicate.trait_ref.args)
            .predicates
            .into_iter()
        {
            let normalized_super_trait = normalize_with_depth_to(
                self,
                obligation.param_env,
                obligation.cause.clone(),
                obligation.recursion_depth + 1,
                super_trait,
                &mut nested,
            );
            nested.push(obligation.with(tcx, normalized_super_trait));
        }

        let assoc_types: Vec<_> = tcx
            .associated_items(trait_predicate.def_id())
            .in_definition_order()
            // Associated types that require `Self: Sized` do not show up in the built-in
            // implementation of `Trait for dyn Trait`, and can be dropped here.
            .filter(|item| !tcx.generics_require_sized_self(item.def_id))
            .filter_map(
                |item| if item.kind == ty::AssocKind::Type { Some(item.def_id) } else { None },
            )
            .collect();

        for assoc_type in assoc_types {
            let defs: &ty::Generics = tcx.generics_of(assoc_type);

            if !defs.params.is_empty() && !tcx.features().generic_associated_types_extended {
                tcx.dcx().span_delayed_bug(
                    obligation.cause.span,
                    "GATs in trait object shouldn't have been considered",
                );
                return Err(SelectionError::TraitNotObjectSafe(trait_predicate.trait_ref.def_id));
            }

            // This maybe belongs in wf, but that can't (doesn't) handle
            // higher-ranked things.
            // Prevent, e.g., `dyn Iterator<Item = str>`.
            for bound in self.tcx().item_bounds(assoc_type).transpose_iter() {
                let arg_bound = if defs.count() == 0 {
                    bound.instantiate(tcx, trait_predicate.trait_ref.args)
                } else {
                    let mut args = smallvec::SmallVec::with_capacity(defs.count());
                    args.extend(trait_predicate.trait_ref.args.iter());
                    let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
                        smallvec::SmallVec::with_capacity(
                            bound.skip_binder().kind().bound_vars().len() + defs.count(),
                        );
                    bound_vars.extend(bound.skip_binder().kind().bound_vars().into_iter());
                    GenericArgs::fill_single(&mut args, defs, &mut |param, _| match param.kind {
                        GenericParamDefKind::Type { .. } => {
                            let kind = ty::BoundTyKind::Param(param.def_id, param.name);
                            let bound_var = ty::BoundVariableKind::Ty(kind);
                            bound_vars.push(bound_var);
                            Ty::new_bound(
                                tcx,
                                ty::INNERMOST,
                                ty::BoundTy {
                                    var: ty::BoundVar::from_usize(bound_vars.len() - 1),
                                    kind,
                                },
                            )
                            .into()
                        }
                        GenericParamDefKind::Lifetime => {
                            let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
                            let bound_var = ty::BoundVariableKind::Region(kind);
                            bound_vars.push(bound_var);
                            ty::Region::new_bound(
                                tcx,
                                ty::INNERMOST,
                                ty::BoundRegion {
                                    var: ty::BoundVar::from_usize(bound_vars.len() - 1),
                                    kind,
                                },
                            )
                            .into()
                        }
                        GenericParamDefKind::Const { .. } => {
                            let bound_var = ty::BoundVariableKind::Const;
                            bound_vars.push(bound_var);
                            ty::Const::new_bound(
                                tcx,
                                ty::INNERMOST,
                                ty::BoundVar::from_usize(bound_vars.len() - 1),
                                tcx.type_of(param.def_id)
                                    .no_bound_vars()
                                    .expect("const parameter types cannot be generic"),
                            )
                            .into()
                        }
                    });
                    let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
                    let assoc_ty_args = tcx.mk_args(&args);
                    let bound =
                        bound.map_bound(|b| b.kind().skip_binder()).instantiate(tcx, assoc_ty_args);
                    ty::Binder::bind_with_vars(bound, bound_vars).to_predicate(tcx)
                };
                let normalized_bound = normalize_with_depth_to(
                    self,
                    obligation.param_env,
                    obligation.cause.clone(),
                    obligation.recursion_depth + 1,
                    arg_bound,
                    &mut nested,
                );
                nested.push(obligation.with(tcx, normalized_bound));
            }
        }

        debug!(?nested, "object nested obligations");

        let vtable_base = vtable_trait_first_method_offset(
            tcx,
            (unnormalized_upcast_trait_ref, ty::Binder::dummy(object_trait_ref)),
        );

        Ok(ImplSource::Builtin(BuiltinImplSource::Object { vtable_base: vtable_base }, nested))
    }

    fn confirm_fn_pointer_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
        fn_host_effect: ty::Const<'tcx>,
    ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
        debug!(?obligation, "confirm_fn_pointer_candidate");

        let tcx = self.tcx();

        let Some(self_ty) = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars()) else {
            // FIXME: Ideally we'd support `for<'a> fn(&'a ()): Fn(&'a ())`,
            // but we do not currently. Luckily, such a bound is not
            // particularly useful, so we don't expect users to write
            // them often.
            return Err(SelectionError::Unimplemented);
        };

        let sig = self_ty.fn_sig(tcx);
        let trait_ref = closure_trait_ref_and_return_type(
            tcx,
            obligation.predicate.def_id(),
            self_ty,
            sig,
            util::TupleArgumentsFlag::Yes,
            fn_host_effect,
        )
        .map_bound(|(trait_ref, _)| trait_ref);

        let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?;
        let cause = obligation.derived_cause(BuiltinDerivedObligation);

        // Confirm the `type Output: Sized;` bound that is present on `FnOnce`
        let output_ty = self.infcx.enter_forall_and_leak_universe(sig.output());
        let output_ty = normalize_with_depth_to(
            self,
            obligation.param_env,
            cause.clone(),
            obligation.recursion_depth,
            output_ty,
            &mut nested,
        );
        let tr = ty::TraitRef::from_lang_item(self.tcx(), LangItem::Sized, cause.span, [output_ty]);
        nested.push(Obligation::new(self.infcx.tcx, cause, obligation.param_env, tr));

        Ok(nested)
    }

    fn confirm_trait_alias_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
    ) -> Vec<PredicateObligation<'tcx>> {
        debug!(?obligation, "confirm_trait_alias_candidate");

        let predicate = self.infcx.enter_forall_and_leak_universe(obligation.predicate);
        let trait_ref = predicate.trait_ref;
        let trait_def_id = trait_ref.def_id;
        let args = trait_ref.args;

        let trait_obligations = self.impl_or_trait_obligations(
            &obligation.cause,
            obligation.recursion_depth,
            obligation.param_env,
            trait_def_id,
            args,
            obligation.predicate,
        );

        debug!(?trait_def_id, ?trait_obligations, "trait alias obligations");

        trait_obligations
    }

    fn confirm_coroutine_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
    ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
        // Okay to skip binder because the args on coroutine types never
        // touch bound regions, they just capture the in-scope
        // type/region parameters.
        let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
        let ty::Coroutine(coroutine_def_id, args) = *self_ty.kind() else {
            bug!("closure candidate for non-closure {:?}", obligation);
        };

        debug!(?obligation, ?coroutine_def_id, ?args, "confirm_coroutine_candidate");

        let coroutine_sig = args.as_coroutine().sig();

        // NOTE: The self-type is a coroutine type and hence is
        // in fact unparameterized (or at least does not reference any
        // regions bound in the obligation).
        let self_ty = obligation
            .predicate
            .self_ty()
            .no_bound_vars()
            .expect("unboxed closure type should not capture bound vars from the predicate");

        let (trait_ref, _, _) = super::util::coroutine_trait_ref_and_outputs(
            self.tcx(),
            obligation.predicate.def_id(),
            self_ty,
            coroutine_sig,
        );

        let nested = self.confirm_poly_trait_refs(obligation, ty::Binder::dummy(trait_ref))?;
        debug!(?trait_ref, ?nested, "coroutine candidate obligations");

        Ok(nested)
    }

    fn confirm_future_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
    ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
        // Okay to skip binder because the args on coroutine types never
        // touch bound regions, they just capture the in-scope
        // type/region parameters.
        let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
        let ty::Coroutine(coroutine_def_id, args) = *self_ty.kind() else {
            bug!("closure candidate for non-closure {:?}", obligation);
        };

        debug!(?obligation, ?coroutine_def_id, ?args, "confirm_future_candidate");

        let coroutine_sig = args.as_coroutine().sig();

        let (trait_ref, _) = super::util::future_trait_ref_and_outputs(
            self.tcx(),
            obligation.predicate.def_id(),
            obligation.predicate.no_bound_vars().expect("future has no bound vars").self_ty(),
            coroutine_sig,
        );

        let nested = self.confirm_poly_trait_refs(obligation, ty::Binder::dummy(trait_ref))?;
        debug!(?trait_ref, ?nested, "future candidate obligations");

        Ok(nested)
    }

    fn confirm_iterator_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
    ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
        // Okay to skip binder because the args on coroutine types never
        // touch bound regions, they just capture the in-scope
        // type/region parameters.
        let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
        let ty::Coroutine(coroutine_def_id, args) = *self_ty.kind() else {
            bug!("closure candidate for non-closure {:?}", obligation);
        };

        debug!(?obligation, ?coroutine_def_id, ?args, "confirm_iterator_candidate");

        let gen_sig = args.as_coroutine().sig();

        let (trait_ref, _) = super::util::iterator_trait_ref_and_outputs(
            self.tcx(),
            obligation.predicate.def_id(),
            obligation.predicate.no_bound_vars().expect("iterator has no bound vars").self_ty(),
            gen_sig,
        );

        let nested = self.confirm_poly_trait_refs(obligation, ty::Binder::dummy(trait_ref))?;
        debug!(?trait_ref, ?nested, "iterator candidate obligations");

        Ok(nested)
    }

    fn confirm_async_iterator_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
    ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
        // Okay to skip binder because the args on coroutine types never
        // touch bound regions, they just capture the in-scope
        // type/region parameters.
        let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
        let ty::Coroutine(coroutine_def_id, args) = *self_ty.kind() else {
            bug!("closure candidate for non-closure {:?}", obligation);
        };

        debug!(?obligation, ?coroutine_def_id, ?args, "confirm_async_iterator_candidate");

        let gen_sig = args.as_coroutine().sig();

        let (trait_ref, _) = super::util::async_iterator_trait_ref_and_outputs(
            self.tcx(),
            obligation.predicate.def_id(),
            obligation.predicate.no_bound_vars().expect("iterator has no bound vars").self_ty(),
            gen_sig,
        );

        let nested = self.confirm_poly_trait_refs(obligation, ty::Binder::dummy(trait_ref))?;
        debug!(?trait_ref, ?nested, "iterator candidate obligations");

        Ok(nested)
    }

    #[instrument(skip(self), level = "debug")]
    fn confirm_closure_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
    ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
        // Okay to skip binder because the args on closure types never
        // touch bound regions, they just capture the in-scope
        // type/region parameters.
        let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());
        let trait_ref = match *self_ty.kind() {
            ty::Closure(_, args) => {
                self.closure_trait_ref_unnormalized(obligation, args, self.tcx().consts.true_)
            }
            ty::CoroutineClosure(_, args) => {
                args.as_coroutine_closure().coroutine_closure_sig().map_bound(|sig| {
                    ty::TraitRef::new(
                        self.tcx(),
                        obligation.predicate.def_id(),
                        [self_ty, sig.tupled_inputs_ty],
                    )
                })
            }
            _ => {
                bug!("closure candidate for non-closure {:?}", obligation);
            }
        };

        self.confirm_poly_trait_refs(obligation, trait_ref)
    }

    #[instrument(skip(self), level = "debug")]
    fn confirm_async_closure_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
    ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
        let tcx = self.tcx();
        let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder());

        let mut nested = vec![];
        let (trait_ref, kind_ty) = match *self_ty.kind() {
            ty::CoroutineClosure(_, args) => {
                let args = args.as_coroutine_closure();
                let trait_ref = args.coroutine_closure_sig().map_bound(|sig| {
                    ty::TraitRef::new(
                        self.tcx(),
                        obligation.predicate.def_id(),
                        [self_ty, sig.tupled_inputs_ty],
                    )
                });
                (trait_ref, args.kind_ty())
            }
            ty::FnDef(..) | ty::FnPtr(..) => {
                let sig = self_ty.fn_sig(tcx);
                let trait_ref = sig.map_bound(|sig| {
                    ty::TraitRef::new(
                        self.tcx(),
                        obligation.predicate.def_id(),
                        [self_ty, Ty::new_tup(tcx, sig.inputs())],
                    )
                });

                // We must additionally check that the return type impls `Future`.

                // FIXME(async_closures): Investigate this before stabilization.
                // We instantiate this binder eagerly because the `confirm_future_candidate`
                // method doesn't support higher-ranked futures, which the `AsyncFn`
                // traits expressly allow the user to write. To fix this correctly,
                // we'd need to instantiate trait bounds before we get to selection,
                // like the new trait solver does.
                let future_trait_def_id = tcx.require_lang_item(LangItem::Future, None);
                let placeholder_output_ty = self.infcx.enter_forall_and_leak_universe(sig.output());
                nested.push(obligation.with(
                    tcx,
                    ty::TraitRef::new(tcx, future_trait_def_id, [placeholder_output_ty]),
                ));

                (trait_ref, Ty::from_closure_kind(tcx, ty::ClosureKind::Fn))
            }
            ty::Closure(_, args) => {
                let args = args.as_closure();
                let sig = args.sig();
                let trait_ref = sig.map_bound(|sig| {
                    ty::TraitRef::new(
                        self.tcx(),
                        obligation.predicate.def_id(),
                        [self_ty, sig.inputs()[0]],
                    )
                });

                // We must additionally check that the return type impls `Future`.
                // See FIXME in last branch for why we instantiate the binder eagerly.
                let future_trait_def_id = tcx.require_lang_item(LangItem::Future, None);
                let placeholder_output_ty = self.infcx.enter_forall_and_leak_universe(sig.output());
                nested.push(obligation.with(
                    tcx,
                    ty::TraitRef::new(tcx, future_trait_def_id, [placeholder_output_ty]),
                ));

                (trait_ref, args.kind_ty())
            }
            _ => bug!("expected callable type for AsyncFn candidate"),
        };

        nested.extend(self.confirm_poly_trait_refs(obligation, trait_ref)?);

        let goal_kind =
            self.tcx().async_fn_trait_kind_from_def_id(obligation.predicate.def_id()).unwrap();

        // If we have not yet determiend the `ClosureKind` of the closure or coroutine-closure,
        // then additionally register an `AsyncFnKindHelper` goal which will fail if the kind
        // is constrained to an insufficient type later on.
        if let Some(closure_kind) = self.infcx.shallow_resolve(kind_ty).to_opt_closure_kind() {
            if !closure_kind.extends(goal_kind) {
                return Err(SelectionError::Unimplemented);
            }
        } else {
            nested.push(obligation.with(
                self.tcx(),
                ty::TraitRef::from_lang_item(
                    self.tcx(),
                    LangItem::AsyncFnKindHelper,
                    obligation.cause.span,
                    [kind_ty, Ty::from_closure_kind(self.tcx(), goal_kind)],
                ),
            ));
        }

        Ok(nested)
    }

    /// In the case of closure types and fn pointers,
    /// we currently treat the input type parameters on the trait as
    /// outputs. This means that when we have a match we have only
    /// considered the self type, so we have to go back and make sure
    /// to relate the argument types too. This is kind of wrong, but
    /// since we control the full set of impls, also not that wrong,
    /// and it DOES yield better error messages (since we don't report
    /// errors as if there is no applicable impl, but rather report
    /// errors are about mismatched argument types.
    ///
    /// Here is an example. Imagine we have a closure expression
    /// and we desugared it so that the type of the expression is
    /// `Closure`, and `Closure` expects `i32` as argument. Then it
    /// is "as if" the compiler generated this impl:
    /// ```ignore (illustrative)
    /// impl Fn(i32) for Closure { ... }
    /// ```
    /// Now imagine our obligation is `Closure: Fn(usize)`. So far
    /// we have matched the self type `Closure`. At this point we'll
    /// compare the `i32` to `usize` and generate an error.
    ///
    /// Note that this checking occurs *after* the impl has selected,
    /// because these output type parameters should not affect the
    /// selection of the impl. Therefore, if there is a mismatch, we
    /// report an error to the user.
    #[instrument(skip(self), level = "trace")]
    fn confirm_poly_trait_refs(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
        self_ty_trait_ref: ty::PolyTraitRef<'tcx>,
    ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
        let obligation_trait_ref =
            self.infcx.enter_forall_and_leak_universe(obligation.predicate.to_poly_trait_ref());
        let self_ty_trait_ref = self.infcx.instantiate_binder_with_fresh_vars(
            obligation.cause.span,
            HigherRankedType,
            self_ty_trait_ref,
        );
        // Normalize the obligation and expected trait refs together, because why not
        let Normalized { obligations: nested, value: (obligation_trait_ref, expected_trait_ref) } =
            ensure_sufficient_stack(|| {
                normalize_with_depth(
                    self,
                    obligation.param_env,
                    obligation.cause.clone(),
                    obligation.recursion_depth + 1,
                    (obligation_trait_ref, self_ty_trait_ref),
                )
            });

        // needed to define opaque types for tests/ui/type-alias-impl-trait/assoc-projection-ice.rs
        self.infcx
            .at(&obligation.cause, obligation.param_env)
            .eq(DefineOpaqueTypes::Yes, obligation_trait_ref, expected_trait_ref)
            .map(|InferOk { mut obligations, .. }| {
                obligations.extend(nested);
                obligations
            })
            .map_err(|terr| {
                SignatureMismatch(Box::new(SignatureMismatchData {
                    expected_trait_ref: ty::Binder::dummy(obligation_trait_ref),
                    found_trait_ref: ty::Binder::dummy(expected_trait_ref),
                    terr,
                }))
            })
    }

    fn confirm_trait_upcasting_unsize_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
        idx: usize,
    ) -> Result<ImplSource<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
        let tcx = self.tcx();

        // `assemble_candidates_for_unsizing` should ensure there are no late-bound
        // regions here. See the comment there for more details.
        let predicate = obligation.predicate.no_bound_vars().unwrap();
        let a_ty = self.infcx.shallow_resolve(predicate.self_ty());
        let b_ty = self.infcx.shallow_resolve(predicate.trait_ref.args.type_at(1));

        let ty::Dynamic(a_data, a_region, ty::Dyn) = *a_ty.kind() else {
            bug!("expected `dyn` type in `confirm_trait_upcasting_unsize_candidate`")
        };
        let ty::Dynamic(b_data, b_region, ty::Dyn) = *b_ty.kind() else {
            bug!("expected `dyn` type in `confirm_trait_upcasting_unsize_candidate`")
        };

        let source_principal = a_data.principal().unwrap().with_self_ty(tcx, a_ty);
        let unnormalized_upcast_principal =
            util::supertraits(tcx, source_principal).nth(idx).unwrap();

        let nested = self
            .match_upcast_principal(
                obligation,
                unnormalized_upcast_principal,
                a_data,
                b_data,
                a_region,
                b_region,
            )?
            .expect("did not expect ambiguity during confirmation");

        let vtable_segment_callback = {
            let mut vptr_offset = 0;
            move |segment| {
                match segment {
                    VtblSegment::MetadataDSA => {
                        vptr_offset += TyCtxt::COMMON_VTABLE_ENTRIES.len();
                    }
                    VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
                        vptr_offset += count_own_vtable_entries(tcx, trait_ref);
                        if trait_ref == unnormalized_upcast_principal {
                            if emit_vptr {
                                return ControlFlow::Break(Some(vptr_offset));
                            } else {
                                return ControlFlow::Break(None);
                            }
                        }

                        if emit_vptr {
                            vptr_offset += 1;
                        }
                    }
                }
                ControlFlow::Continue(())
            }
        };

        let vtable_vptr_slot =
            prepare_vtable_segments(tcx, source_principal, vtable_segment_callback).unwrap();

        Ok(ImplSource::Builtin(BuiltinImplSource::TraitUpcasting { vtable_vptr_slot }, nested))
    }

    fn confirm_builtin_unsize_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
    ) -> Result<ImplSource<'tcx, PredicateObligation<'tcx>>, SelectionError<'tcx>> {
        let tcx = self.tcx();

        // `assemble_candidates_for_unsizing` should ensure there are no late-bound
        // regions here. See the comment there for more details.
        let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap());
        let target = obligation.predicate.skip_binder().trait_ref.args.type_at(1);
        let target = self.infcx.shallow_resolve(target);
        debug!(?source, ?target, "confirm_builtin_unsize_candidate");

        Ok(match (source.kind(), target.kind()) {
            // Trait+Kx+'a -> Trait+Ky+'b (auto traits and lifetime subtyping).
            (&ty::Dynamic(data_a, r_a, dyn_a), &ty::Dynamic(data_b, r_b, dyn_b))
                if dyn_a == dyn_b =>
            {
                // See `assemble_candidates_for_unsizing` for more info.
                // We already checked the compatibility of auto traits within `assemble_candidates_for_unsizing`.
                let iter = data_a
                    .principal()
                    .map(|b| b.map_bound(ty::ExistentialPredicate::Trait))
                    .into_iter()
                    .chain(
                        data_a
                            .projection_bounds()
                            .map(|b| b.map_bound(ty::ExistentialPredicate::Projection)),
                    )
                    .chain(
                        data_b
                            .auto_traits()
                            .map(ty::ExistentialPredicate::AutoTrait)
                            .map(ty::Binder::dummy),
                    );
                let existential_predicates = tcx.mk_poly_existential_predicates_from_iter(iter);
                let source_trait = Ty::new_dynamic(tcx, existential_predicates, r_b, dyn_a);

                // Require that the traits involved in this upcast are **equal**;
                // only the **lifetime bound** is changed.
                let InferOk { mut obligations, .. } = self
                    .infcx
                    .at(&obligation.cause, obligation.param_env)
                    .sup(DefineOpaqueTypes::No, target, source_trait)
                    .map_err(|_| Unimplemented)?;

                // Register one obligation for 'a: 'b.
                let outlives = ty::OutlivesPredicate(r_a, r_b);
                obligations.push(Obligation::with_depth(
                    tcx,
                    obligation.cause.clone(),
                    obligation.recursion_depth + 1,
                    obligation.param_env,
                    obligation.predicate.rebind(outlives),
                ));

                ImplSource::Builtin(BuiltinImplSource::Misc, obligations)
            }

            // `T` -> `Trait`
            (_, &ty::Dynamic(data, r, ty::Dyn)) => {
                let mut object_dids = data.auto_traits().chain(data.principal_def_id());
                if let Some(did) = object_dids.find(|did| !tcx.check_is_object_safe(*did)) {
                    return Err(TraitNotObjectSafe(did));
                }

                let predicate_to_obligation = |predicate| {
                    Obligation::with_depth(
                        tcx,
                        obligation.cause.clone(),
                        obligation.recursion_depth + 1,
                        obligation.param_env,
                        predicate,
                    )
                };

                // Create obligations:
                //  - Casting `T` to `Trait`
                //  - For all the various builtin bounds attached to the object cast. (In other
                //  words, if the object type is `Foo + Send`, this would create an obligation for
                //  the `Send` check.)
                //  - Projection predicates
                let mut nested: Vec<_> = data
                    .iter()
                    .map(|predicate| predicate_to_obligation(predicate.with_self_ty(tcx, source)))
                    .collect();

                // We can only make objects from sized types.
                let tr = ty::TraitRef::from_lang_item(
                    tcx,
                    LangItem::Sized,
                    obligation.cause.span,
                    [source],
                );
                nested.push(predicate_to_obligation(tr.to_predicate(tcx)));

                // If the type is `Foo + 'a`, ensure that the type
                // being cast to `Foo + 'a` outlives `'a`:
                let outlives = ty::OutlivesPredicate(source, r);
                nested.push(predicate_to_obligation(
                    ty::Binder::dummy(ty::ClauseKind::TypeOutlives(outlives)).to_predicate(tcx),
                ));

                ImplSource::Builtin(BuiltinImplSource::Misc, nested)
            }

            // `[T; n]` -> `[T]`
            (&ty::Array(a, _), &ty::Slice(b)) => {
                let InferOk { obligations, .. } = self
                    .infcx
                    .at(&obligation.cause, obligation.param_env)
                    .eq(DefineOpaqueTypes::No, b, a)
                    .map_err(|_| Unimplemented)?;

                ImplSource::Builtin(BuiltinImplSource::Misc, obligations)
            }

            // `Struct<T>` -> `Struct<U>`
            (&ty::Adt(def, args_a), &ty::Adt(_, args_b)) => {
                let unsizing_params = tcx.unsizing_params_for_adt(def.did());
                if unsizing_params.is_empty() {
                    return Err(Unimplemented);
                }

                let tail_field = def.non_enum_variant().tail();
                let tail_field_ty = tcx.type_of(tail_field.did);

                let mut nested = vec![];

                // Extract `TailField<T>` and `TailField<U>` from `Struct<T>` and `Struct<U>`,
                // normalizing in the process, since `type_of` returns something directly from
                // astconv (which means it's un-normalized).
                let source_tail = normalize_with_depth_to(
                    self,
                    obligation.param_env,
                    obligation.cause.clone(),
                    obligation.recursion_depth + 1,
                    tail_field_ty.instantiate(tcx, args_a),
                    &mut nested,
                );
                let target_tail = normalize_with_depth_to(
                    self,
                    obligation.param_env,
                    obligation.cause.clone(),
                    obligation.recursion_depth + 1,
                    tail_field_ty.instantiate(tcx, args_b),
                    &mut nested,
                );

                // Check that the source struct with the target's
                // unsizing parameters is equal to the target.
                let args =
                    tcx.mk_args_from_iter(args_a.iter().enumerate().map(|(i, k)| {
                        if unsizing_params.contains(i as u32) { args_b[i] } else { k }
                    }));
                let new_struct = Ty::new_adt(tcx, def, args);
                let InferOk { obligations, .. } = self
                    .infcx
                    .at(&obligation.cause, obligation.param_env)
                    .eq(DefineOpaqueTypes::No, target, new_struct)
                    .map_err(|_| Unimplemented)?;
                nested.extend(obligations);

                // Construct the nested `TailField<T>: Unsize<TailField<U>>` predicate.
                let tail_unsize_obligation = obligation.with(
                    tcx,
                    ty::TraitRef::new(
                        tcx,
                        obligation.predicate.def_id(),
                        [source_tail, target_tail],
                    ),
                );
                nested.push(tail_unsize_obligation);

                ImplSource::Builtin(BuiltinImplSource::Misc, nested)
            }

            // `(.., T)` -> `(.., U)`
            (&ty::Tuple(tys_a), &ty::Tuple(tys_b)) => {
                assert_eq!(tys_a.len(), tys_b.len());

                // The last field of the tuple has to exist.
                let (&a_last, a_mid) = tys_a.split_last().ok_or(Unimplemented)?;
                let &b_last = tys_b.last().unwrap();

                // Check that the source tuple with the target's
                // last element is equal to the target.
                let new_tuple =
                    Ty::new_tup_from_iter(tcx, a_mid.iter().copied().chain(iter::once(b_last)));
                let InferOk { mut obligations, .. } = self
                    .infcx
                    .at(&obligation.cause, obligation.param_env)
                    .eq(DefineOpaqueTypes::No, target, new_tuple)
                    .map_err(|_| Unimplemented)?;

                // Add a nested `T: Unsize<U>` predicate.
                let last_unsize_obligation = obligation.with(
                    tcx,
                    ty::TraitRef::new(tcx, obligation.predicate.def_id(), [a_last, b_last]),
                );
                obligations.push(last_unsize_obligation);

                ImplSource::Builtin(BuiltinImplSource::TupleUnsizing, obligations)
            }

            _ => bug!("source: {source}, target: {target}"),
        })
    }

    fn confirm_const_destruct_candidate(
        &mut self,
        obligation: &PolyTraitObligation<'tcx>,
        impl_def_id: Option<DefId>,
    ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> {
        let Some(host_effect_index) =
            self.tcx().generics_of(obligation.predicate.def_id()).host_effect_index
        else {
            bug!()
        };
        let host_effect_param: ty::GenericArg<'tcx> =
            obligation.predicate.skip_binder().trait_ref.args.const_at(host_effect_index).into();

        let drop_trait = self.tcx().require_lang_item(LangItem::Drop, None);

        let tcx = self.tcx();
        let self_ty = self.infcx.shallow_resolve(obligation.self_ty());

        let mut nested = vec![];
        let cause = obligation.derived_cause(BuiltinDerivedObligation);

        // If we have a custom `impl const Drop`, then
        // first check it like a regular impl candidate.
        // This is copied from confirm_impl_candidate but remaps the predicate to `~const Drop` beforehand.
        if let Some(impl_def_id) = impl_def_id {
            let mut new_obligation = obligation.clone();
            new_obligation.predicate = new_obligation.predicate.map_bound(|mut trait_pred| {
                trait_pred.trait_ref.def_id = drop_trait;
                trait_pred
            });
            let args = self.rematch_impl(impl_def_id, &new_obligation);
            debug!(?args, "impl args");

            let cause = obligation.derived_cause(|derived| {
                ImplDerivedObligation(Box::new(ImplDerivedObligationCause {
                    derived,
                    impl_or_alias_def_id: impl_def_id,
                    impl_def_predicate_index: None,
                    span: obligation.cause.span,
                }))
            });
            let obligations = ensure_sufficient_stack(|| {
                self.vtable_impl(
                    impl_def_id,
                    args,
                    &cause,
                    new_obligation.recursion_depth + 1,
                    new_obligation.param_env,
                    obligation.predicate,
                )
            });
            nested.extend(obligations.nested);
        }

        // We want to confirm the ADT's fields if we have an ADT
        let mut stack = match *self_ty.skip_binder().kind() {
            ty::Adt(def, args) => def.all_fields().map(|f| f.ty(tcx, args)).collect(),
            _ => vec![self_ty.skip_binder()],
        };

        while let Some(nested_ty) = stack.pop() {
            match *nested_ty.kind() {
                // We know these types are trivially drop
                ty::Bool
                | ty::Char
                | ty::Int(_)
                | ty::Uint(_)
                | ty::Float(_)
                | ty::Infer(ty::IntVar(_))
                | ty::Infer(ty::FloatVar(_))
                | ty::Str
                | ty::RawPtr(_)
                | ty::Ref(..)
                | ty::FnDef(..)
                | ty::FnPtr(_)
                | ty::Never
                | ty::Foreign(_) => {}

                // `ManuallyDrop` is trivially drop
                ty::Adt(def, _) if Some(def.did()) == tcx.lang_items().manually_drop() => {}

                // These types are built-in, so we can fast-track by registering
                // nested predicates for their constituent type(s)
                ty::Array(ty, _) | ty::Slice(ty) => {
                    stack.push(ty);
                }
                ty::Tuple(tys) => {
                    stack.extend(tys.iter());
                }
                ty::Closure(_, args) => {
                    stack.push(args.as_closure().tupled_upvars_ty());
                }
                ty::Coroutine(_, args) => {
                    let coroutine = args.as_coroutine();
                    stack.extend([coroutine.tupled_upvars_ty(), coroutine.witness()]);
                }
                ty::CoroutineWitness(def_id, args) => {
                    let tcx = self.tcx();
                    stack.extend(tcx.coroutine_hidden_types(def_id).map(|bty| {
                        let ty = bty.instantiate(tcx, args);
                        debug_assert!(!ty.has_bound_regions());
                        ty
                    }))
                }

                // If we have a projection type, make sure to normalize it so we replace it
                // with a fresh infer variable
                ty::Alias(ty::Projection | ty::Inherent, ..) => {
                    let predicate = normalize_with_depth_to(
                        self,
                        obligation.param_env,
                        cause.clone(),
                        obligation.recursion_depth + 1,
                        self_ty.rebind(ty::TraitPredicate {
                            trait_ref: ty::TraitRef::from_lang_item(
                                self.tcx(),
                                LangItem::Destruct,
                                cause.span,
                                [nested_ty.into(), host_effect_param],
                            ),
                            polarity: ty::ImplPolarity::Positive,
                        }),
                        &mut nested,
                    );

                    nested.push(Obligation::with_depth(
                        tcx,
                        cause.clone(),
                        obligation.recursion_depth + 1,
                        obligation.param_env,
                        predicate,
                    ));
                }

                // If we have any other type (e.g. an ADT), just register a nested obligation
                // since it's either not `const Drop` (and we raise an error during selection),
                // or it's an ADT (and we need to check for a custom impl during selection)
                _ => {
                    let predicate = self_ty.rebind(ty::TraitPredicate {
                        trait_ref: ty::TraitRef::from_lang_item(
                            self.tcx(),
                            LangItem::Destruct,
                            cause.span,
                            [nested_ty.into(), host_effect_param],
                        ),
                        polarity: ty::ImplPolarity::Positive,
                    });

                    nested.push(Obligation::with_depth(
                        tcx,
                        cause.clone(),
                        obligation.recursion_depth + 1,
                        obligation.param_env,
                        predicate,
                    ));
                }
            }
        }

        Ok(nested)
    }
}