-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathCSSolver.cpp
2610 lines (2162 loc) · 88.1 KB
/
CSSolver.cpp
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
//===--- CSSolver.cpp - Constraint Solver ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the constraint solver used in the type checker.
//
//===----------------------------------------------------------------------===//
#include "CSStep.h"
#include "TypeCheckType.h"
#include "TypeChecker.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/TypeWalker.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/Sema/ConstraintGraph.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/SolutionResult.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <memory>
#include <tuple>
using namespace swift;
using namespace constraints;
//===----------------------------------------------------------------------===//
// Constraint solver statistics
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "Constraint solver overall"
#define JOIN2(X,Y) X##Y
STATISTIC(NumSolutionAttempts, "# of solution attempts");
STATISTIC(TotalNumTypeVariables, "# of type variables created");
#define CS_STATISTIC(Name, Description) \
STATISTIC(Overall##Name, Description);
#include "swift/Sema/ConstraintSolverStats.def"
#undef DEBUG_TYPE
#define DEBUG_TYPE "Constraint solver largest system"
#define CS_STATISTIC(Name, Description) \
STATISTIC(Largest##Name, Description);
#include "swift/Sema/ConstraintSolverStats.def"
STATISTIC(LargestSolutionAttemptNumber, "# of the largest solution attempt");
TypeVariableType *ConstraintSystem::createTypeVariable(
ConstraintLocator *locator,
unsigned options) {
++TotalNumTypeVariables;
auto tv = TypeVariableType::getNew(getASTContext(), assignTypeVariableID(),
locator, options);
addTypeVariable(tv);
return tv;
}
Solution ConstraintSystem::finalize() {
assert(solverState);
// Create the solution.
Solution solution(*this, CurrentScore);
// Update the best score we've seen so far.
auto &ctx = getASTContext();
assert(ctx.TypeCheckerOpts.DisableConstraintSolverPerformanceHacks ||
!solverState->BestScore || CurrentScore <= *solverState->BestScore);
if (!solverState->BestScore || CurrentScore <= *solverState->BestScore) {
solverState->BestScore = CurrentScore;
}
for (auto tv : getTypeVariables()) {
if (getFixedType(tv))
continue;
switch (solverState->AllowFreeTypeVariables) {
case FreeTypeVariableBinding::Disallow:
llvm_unreachable("Solver left free type variables");
case FreeTypeVariableBinding::Allow:
break;
case FreeTypeVariableBinding::UnresolvedType:
assignFixedType(tv, ctx.TheUnresolvedType);
break;
}
}
// For each of the type variables, get its fixed type.
for (auto tv : getTypeVariables()) {
// This type variable has no binding. Allowed only
// when `FreeTypeVariableBinding::Allow` is set,
// which is checked above.
if (!getFixedType(tv)) {
solution.typeBindings[tv] = Type();
continue;
}
solution.typeBindings[tv] = simplifyType(tv)->reconstituteSugar(false);
}
// Copy over the resolved overloads.
solution.overloadChoices.insert(ResolvedOverloads.begin(),
ResolvedOverloads.end());
// For each of the constraint restrictions, record it with simplified,
// canonical types.
if (solverState) {
for (const auto &entry : ConstraintRestrictions) {
const auto &types = entry.first;
auto restriction = entry.second;
CanType first = simplifyType(types.first)->getCanonicalType();
CanType second = simplifyType(types.second)->getCanonicalType();
// Pick the restriction with the highest value to avoid depending on
// iteration order.
auto found = solution.ConstraintRestrictions.find({first, second});
if (found != solution.ConstraintRestrictions.end() &&
(unsigned) restriction <= (unsigned) found->second) {
continue;
}
solution.ConstraintRestrictions[{first, second}] = restriction;
}
}
// For each of the fixes, record it as an operation on the affected
// expression.
unsigned firstFixIndex =
(solverState ? solverState->numPartialSolutionFixes : 0);
for (const auto &fix :
llvm::make_range(Fixes.begin() + firstFixIndex, Fixes.end()))
solution.Fixes.push_back(fix);
for (const auto &fix : FixedRequirements) {
solution.FixedRequirements.push_back(fix);
}
// Remember all the disjunction choices we made.
for (auto &choice : DisjunctionChoices) {
solution.DisjunctionChoices.insert(choice);
}
// Remember all the applied disjunctions.
for (auto &choice : AppliedDisjunctions) {
solution.AppliedDisjunctions.insert(choice);
}
// Remember all of the argument/parameter matching choices we made.
for (auto &argumentMatch : argumentMatchingChoices) {
auto inserted = solution.argumentMatchingChoices.insert(argumentMatch);
assert(inserted.second || inserted.first->second == argumentMatch.second);
(void)inserted;
}
// Remember implied results.
for (auto impliedResult : ImpliedResults)
solution.ImpliedResults.insert(impliedResult);
// Remember the opened types.
for (const auto &opened : OpenedTypes) {
// We shouldn't ever register opened types multiple times,
// but saving and re-applying solutions can cause us to get
// multiple entries. We should use an optimized PartialSolution
// structure for that use case, which would optimize a lot of
// stuff here.
#if false
assert((solution.OpenedTypes.count(opened.first) == 0 ||
solution.OpenedTypes[opened.first] == opened.second)
&& "Already recorded");
#endif
solution.OpenedTypes.insert(opened);
}
// Remember the opened existential types.
for (auto &openedExistential : OpenedExistentialTypes) {
openedExistential.second = simplifyType(openedExistential.second)
->castTo<ExistentialArchetypeType>();
assert(solution.OpenedExistentialTypes.count(openedExistential.first) == 0||
solution.OpenedExistentialTypes[openedExistential.first]
== openedExistential.second &&
"Already recorded");
solution.OpenedExistentialTypes.insert(openedExistential);
}
for (const auto &expansion : OpenedPackExpansionTypes) {
assert(solution.OpenedPackExpansionTypes.count(expansion.first) == 0 ||
solution.OpenedPackExpansionTypes[expansion.first] ==
expansion.second &&
"Already recorded");
solution.OpenedPackExpansionTypes.insert(expansion);
}
// Remember the defaulted type variables.
solution.DefaultedConstraints.insert(DefaultedConstraints.begin(),
DefaultedConstraints.end());
for (auto &nodeType : NodeTypes) {
solution.nodeTypes.insert(nodeType);
}
for (auto &keyPathComponentType : KeyPathComponentTypes) {
solution.keyPathComponentTypes.insert(keyPathComponentType);
}
// Remember key paths.
for (const auto &keyPaths : KeyPaths) {
solution.KeyPaths.insert(keyPaths);
}
// Remember contextual types.
for (auto &entry : contextualTypes) {
solution.contextualTypes.push_back({entry.first, entry.second.first});
}
for (auto &target : targets)
solution.targets.insert(target);
for (const auto &item : caseLabelItems)
solution.caseLabelItems.insert(item);
for (const auto &throwSite : potentialThrowSites)
solution.potentialThrowSites.push_back(throwSite);
for (const auto &pattern : exprPatterns)
solution.exprPatterns.insert(pattern);
for (const auto ¶m : isolatedParams)
solution.isolatedParams.insert(param);
for (auto closure : preconcurrencyClosures)
solution.preconcurrencyClosures.insert(closure);
for (const auto &transformed : resultBuilderTransformed) {
solution.resultBuilderTransformed.insert(transformed);
}
for (const auto &appliedWrapper : appliedPropertyWrappers) {
solution.appliedPropertyWrappers.insert(appliedWrapper);
}
// Remember argument lists.
for (const auto &argListMapping : ArgumentLists) {
solution.argumentLists.insert(argListMapping);
}
for (const auto &implicitRoot : ImplicitCallAsFunctionRoots) {
solution.ImplicitCallAsFunctionRoots.insert(implicitRoot);
}
for (const auto &env : PackExpansionEnvironments) {
solution.PackExpansionEnvironments.insert(env);
}
for (const auto &packEnv : PackElementExpansions)
solution.PackElementExpansions.insert(packEnv);
for (const auto &synthesized : SynthesizedConformances) {
solution.SynthesizedConformances.insert(synthesized);
}
return solution;
}
void ConstraintSystem::replaySolution(const Solution &solution,
bool shouldIncreaseScore) {
if (shouldIncreaseScore)
replayScore(solution.getFixedScore());
for (auto binding : solution.typeBindings) {
// If we haven't seen this type variable before, record it now.
addTypeVariable(binding.first);
}
// Assign fixed types to the type variables solved by this solution.
for (auto binding : solution.typeBindings) {
if (!binding.second)
continue;
// If we don't already have a fixed type for this type variable,
// assign the fixed type from the solution.
if (getFixedType(binding.first))
continue;
assignFixedType(binding.first, binding.second, /*updateState=*/false);
}
// Register overload choices.
// FIXME: Copy these directly into some kind of partial solution?
for (auto overload : solution.overloadChoices) {
if (!ResolvedOverloads.count(overload.first))
recordResolvedOverload(overload.first, overload.second);
}
// Register constraint restrictions.
// FIXME: Copy these directly into some kind of partial solution?
for ( auto &restriction : solution.ConstraintRestrictions) {
auto type1 = restriction.first.first;
auto type2 = restriction.first.second;
addConversionRestriction(type1, type2, restriction.second);
}
// Register the solution's disjunction choices.
for (auto &choice : solution.DisjunctionChoices) {
if (DisjunctionChoices.count(choice.first) == 0)
recordDisjunctionChoice(choice.first, choice.second);
}
// Register the solution's applied disjunctions.
for (auto &choice : solution.AppliedDisjunctions) {
if (AppliedDisjunctions.count(choice.first) == 0)
recordAppliedDisjunction(choice.first, choice.second);
}
// Remember all of the argument/parameter matching choices we made.
for (auto &argumentMatch : solution.argumentMatchingChoices) {
if (argumentMatchingChoices.count(argumentMatch.first) == 0)
recordMatchCallArgumentResult(argumentMatch.first, argumentMatch.second);
}
// Remember implied results.
for (auto impliedResult : solution.ImpliedResults) {
if (ImpliedResults.count(impliedResult.first) == 0)
recordImpliedResult(impliedResult.first, impliedResult.second);
}
// Register the solution's opened types.
for (const auto &opened : solution.OpenedTypes) {
if (OpenedTypes.count(opened.first) == 0)
recordOpenedType(opened.first, opened.second);
}
// Register the solution's opened existential types.
for (const auto &openedExistential : solution.OpenedExistentialTypes) {
if (OpenedExistentialTypes.count(openedExistential.first) == 0) {
recordOpenedExistentialType(openedExistential.first,
openedExistential.second);
}
}
// Register the solution's opened pack expansion types.
for (const auto &expansion : solution.OpenedPackExpansionTypes) {
if (OpenedPackExpansionTypes.count(expansion.first) == 0)
recordOpenedPackExpansionType(expansion.first, expansion.second);
}
// Register the solutions's pack expansion environments.
for (const auto &expansion : solution.PackExpansionEnvironments) {
if (PackExpansionEnvironments.count(expansion.first) == 0)
recordPackExpansionEnvironment(expansion.first, expansion.second);
}
// Register the solutions's pack expansions.
for (auto &packEnvironment : solution.PackElementExpansions) {
if (PackElementExpansions.count(packEnvironment.first) == 0)
recordPackElementExpansion(packEnvironment.first, packEnvironment.second);
}
// Register the defaulted type variables.
for (auto *locator : solution.DefaultedConstraints) {
recordDefaultedConstraint(locator);
}
// Add the node types back.
for (auto &nodeType : solution.nodeTypes) {
setType(nodeType.first, nodeType.second);
}
for (auto &nodeType : solution.keyPathComponentTypes) {
setType(nodeType.getFirst().first, nodeType.getFirst().second,
nodeType.getSecond());
}
// Add key paths.
for (const auto &keypath : solution.KeyPaths) {
if (KeyPaths.count(keypath.first) == 0) {
recordKeyPath(keypath.first,
std::get<0>(keypath.second),
std::get<1>(keypath.second),
std::get<2>(keypath.second));
}
}
// Add the contextual types.
for (const auto &contextualType : solution.contextualTypes) {
if (!getContextualTypeInfo(contextualType.first))
setContextualInfo(contextualType.first, contextualType.second);
}
// Register the statement condition targets.
for (const auto &target : solution.targets) {
if (!getTargetFor(target.first))
setTargetFor(target.first, target.second);
}
// Register the statement condition targets.
for (const auto &info : solution.caseLabelItems) {
if (!getCaseLabelItemInfo(info.first))
setCaseLabelItemInfo(info.first, info.second);
}
auto sites = ArrayRef(solution.potentialThrowSites);
ASSERT(sites.size() >= potentialThrowSites.size());
for (const auto &site : sites.slice(potentialThrowSites.size())) {
potentialThrowSites.push_back(site);
}
for (auto param : solution.isolatedParams) {
if (isolatedParams.count(param) == 0)
recordIsolatedParam(param);
}
for (auto &pair : solution.exprPatterns) {
if (exprPatterns.count(pair.first) == 0)
setExprPatternFor(pair.first, pair.second);
}
for (auto closure : solution.preconcurrencyClosures) {
if (preconcurrencyClosures.count(closure) == 0)
recordPreconcurrencyClosure(closure);
}
for (const auto &transformed : solution.resultBuilderTransformed) {
if (resultBuilderTransformed.count(transformed.first) == 0)
recordResultBuilderTransform(transformed.first, transformed.second);
}
for (const auto &appliedWrapper : solution.appliedPropertyWrappers) {
auto found = appliedPropertyWrappers.find(appliedWrapper.first);
if (found == appliedPropertyWrappers.end()) {
for (auto applied : appliedWrapper.second)
applyPropertyWrapper(getAsExpr(appliedWrapper.first), applied);
} else {
ASSERT(found->second.size() == appliedWrapper.second.size());
}
}
// Register the argument lists.
for (auto &argListMapping : solution.argumentLists) {
if (ArgumentLists.count(argListMapping.first) == 0)
recordArgumentList(argListMapping.first, argListMapping.second);
}
for (auto &implicitRoot : solution.ImplicitCallAsFunctionRoots) {
if (ImplicitCallAsFunctionRoots.count(implicitRoot.first) == 0)
recordImplicitCallAsFunctionRoot(implicitRoot.first, implicitRoot.second);
}
for (auto &synthesized : solution.SynthesizedConformances) {
if (SynthesizedConformances.count(synthesized.first) == 0)
recordSynthesizedConformance(synthesized.first, synthesized.second);
}
// Register any fixes produced along this path.
for (auto *fix : solution.Fixes) {
if (Fixes.count(fix) == 0)
addFix(fix);
}
// Register fixed requirements.
for (auto fix : solution.FixedRequirements) {
recordFixedRequirement(std::get<0>(fix),
std::get<1>(fix),
std::get<2>(fix));
}
}
bool ConstraintSystem::simplify() {
// While we have a constraint in the worklist, process it.
while (!ActiveConstraints.empty()) {
// Grab the next constraint from the worklist.
auto *constraint = &ActiveConstraints.front();
deactivateConstraint(constraint);
auto isSimplifiable =
constraint->getKind() != ConstraintKind::Disjunction &&
constraint->getKind() != ConstraintKind::Conjunction;
if (isDebugMode()) {
auto &log = llvm::errs();
log.indent(solverState->getCurrentIndent());
log << "(considering: ";
constraint->print(log, &getASTContext().SourceMgr,
solverState->getCurrentIndent());
log << "\n";
// {Dis, Con}junction are returned unsolved in \c simplifyConstraint() and
// handled separately by solver steps.
if (isSimplifiable) {
log.indent(solverState->getCurrentIndent() + 2)
<< "(simplification result:\n";
}
}
// Simplify this constraint.
switch (simplifyConstraint(*constraint)) {
case SolutionKind::Error:
retireFailedConstraint(constraint);
if (isDebugMode()) {
auto &log = llvm::errs();
if (isSimplifiable) {
log.indent(solverState->getCurrentIndent() + 2) << ")\n";
}
log.indent(solverState->getCurrentIndent() + 2) << "(outcome: error)\n";
}
break;
case SolutionKind::Solved:
if (solverState)
++solverState->NumSimplifiedConstraints;
retireConstraint(constraint);
if (isDebugMode()) {
auto &log = llvm::errs();
if (isSimplifiable) {
log.indent(solverState->getCurrentIndent() + 2) << ")\n";
}
log.indent(solverState->getCurrentIndent() + 2)
<< "(outcome: simplified)\n";
}
break;
case SolutionKind::Unsolved:
if (solverState)
++solverState->NumUnsimplifiedConstraints;
if (isDebugMode()) {
auto &log = llvm::errs();
if (isSimplifiable) {
log.indent(solverState->getCurrentIndent() + 2) << ")\n";
}
log.indent(solverState->getCurrentIndent() + 2)
<< "(outcome: unsolved)\n";
}
break;
}
if (isDebugMode()) {
auto &log = llvm::errs();
log.indent(solverState->getCurrentIndent()) << ")\n";
}
// Check whether a constraint failed. If so, we're done.
if (failedConstraint) {
return true;
}
// If the current score is worse than the best score we've seen so far,
// there's no point in continuing. So don't.
if (worseThanBestSolution()) {
return true;
}
}
return false;
}
namespace {
template<typename T>
void truncate(std::vector<T> &vec, unsigned newSize) {
assert(newSize <= vec.size() && "Not a truncation!");
vec.erase(vec.begin() + newSize, vec.end());
}
/// Truncate the given small vector to the given new size.
template<typename T>
void truncate(SmallVectorImpl<T> &vec, unsigned newSize) {
assert(newSize <= vec.size() && "Not a truncation!");
vec.erase(vec.begin() + newSize, vec.end());
}
template<typename T, unsigned N>
void truncate(llvm::SmallSetVector<T, N> &vec, unsigned newSize) {
assert(newSize <= vec.size() && "Not a truncation!");
for (unsigned i = 0, n = vec.size() - newSize; i != n; ++i)
vec.pop_back();
}
template <typename K, typename V>
void truncate(llvm::MapVector<K, V> &map, unsigned newSize) {
assert(newSize <= map.size() && "Not a truncation!");
for (unsigned i = 0, n = map.size() - newSize; i != n; ++i)
map.pop_back();
}
template <typename K, typename V, unsigned N>
void truncate(llvm::SmallMapVector<K, V, N> &map, unsigned newSize) {
assert(newSize <= map.size() && "Not a truncation!");
for (unsigned i = 0, n = map.size() - newSize; i != n; ++i)
map.pop_back();
}
template <typename V>
void truncate(llvm::SetVector<V> &vector, unsigned newSize) {
while (vector.size() > newSize)
vector.pop_back();
}
} // end anonymous namespace
ConstraintSystem::SolverState::SolverState(
ConstraintSystem &cs, FreeTypeVariableBinding allowFreeTypeVariables)
: CS(cs), AllowFreeTypeVariables(allowFreeTypeVariables), Trail(cs) {
assert(!CS.solverState &&
"Constraint system should not already have solver state!");
CS.solverState = this;
++NumSolutionAttempts;
SolutionAttempt = NumSolutionAttempts;
// Record active constraints for re-activation at the end of lifetime.
for (auto &constraint : cs.ActiveConstraints)
activeConstraints.push_back(&constraint);
// If we're supposed to debug a specific constraint solver attempt,
// turn on debugging now.
ASTContext &ctx = CS.getASTContext();
const auto &tyOpts = ctx.TypeCheckerOpts;
if (tyOpts.DebugConstraintSolverAttempt &&
tyOpts.DebugConstraintSolverAttempt == SolutionAttempt) {
CS.Options |= ConstraintSystemFlags::DebugConstraints;
llvm::errs().indent(CS.solverState->getCurrentIndent())
<< "---Constraint system #" << SolutionAttempt << "---\n";
CS.print(llvm::errs());
}
}
ConstraintSystem::SolverState::~SolverState() {
assert((CS.solverState == this) &&
"Expected constraint system to have this solver state!");
CS.solverState = nullptr;
// If constraint system ended up being in an invalid state
// let's just drop the state without attempting to rollback.
if (CS.inInvalidState())
return;
// Re-activate constraints which were initially marked as "active"
// to restore original state of the constraint system.
for (auto *constraint : activeConstraints) {
// If the constraint is already active we can just move on.
if (constraint->isActive())
continue;
#ifndef NDEBUG
// Make sure that constraint is present in the "inactive" set
// before transferring it to "active".
auto existing = llvm::find_if(CS.InactiveConstraints,
[&constraint](const Constraint &inactive) {
return &inactive == constraint;
});
assert(existing != CS.InactiveConstraints.end() &&
"All constraints should be present in 'inactive' list");
#endif
// Transfer the constraint to "active" set.
CS.activateConstraint(constraint);
}
// If global constraint debugging is off and we are finished logging the
// current solution attempt, switch debugging back off.
const auto &tyOpts = CS.getASTContext().TypeCheckerOpts;
if (!tyOpts.DebugConstraintSolver &&
tyOpts.DebugConstraintSolverAttempt &&
tyOpts.DebugConstraintSolverAttempt == SolutionAttempt) {
CS.Options -= ConstraintSystemFlags::DebugConstraints;
}
// This statistic is special because it's not a counter; we just update
// it in one shot at the end.
ASTBytesAllocated = CS.getASTContext().getSolverMemory();
// Write our local statistics back to the overall statistics.
#define CS_STATISTIC(Name, Description) JOIN2(Overall,Name) += Name;
#include "swift/Sema/ConstraintSolverStats.def"
#if LLVM_ENABLE_STATS
// Update the "largest" statistics if this system is larger than the
// previous one.
// FIXME: This is not at all thread-safe.
if (NumSolverScopes > LargestNumSolverScopes.getValue()) {
LargestSolutionAttemptNumber = SolutionAttempt-1;
++LargestSolutionAttemptNumber;
#define CS_STATISTIC(Name, Description) \
JOIN2(Largest,Name) = Name-1; \
++JOIN2(Largest,Name);
#include "swift/Sema/ConstraintSolverStats.def"
}
#endif
}
ConstraintSystem::SolverScope::SolverScope(ConstraintSystem &cs)
: cs(cs),
startTypeVariables(cs.TypeVariables.size()),
startTrailSteps(cs.solverState->Trail.size()),
scopeNumber(cs.solverState->beginScope()),
moved(0) {
ASSERT(!cs.failedConstraint && "Unexpected failed constraint!");
}
ConstraintSystem::SolverScope::SolverScope(SolverScope &&other)
: cs(other.cs),
startTypeVariables(other.startTypeVariables),
startTrailSteps(other.startTrailSteps),
scopeNumber(other.scopeNumber),
moved(0) {
other.moved = 1;
}
ConstraintSystem::SolverScope::~SolverScope() {
if (moved)
return;
// Don't attempt to rollback from an incorrect state.
if (cs.inInvalidState())
return;
// Roll back introduced type variables.
truncate(cs.TypeVariables, startTypeVariables);
// Move any remaining active constraints into the inactive list.
if (!cs.ActiveConstraints.empty()) {
for (auto &constraint : cs.ActiveConstraints) {
constraint.setActive(false);
}
cs.InactiveConstraints.splice(cs.InactiveConstraints.end(),
cs.ActiveConstraints);
}
uint64_t endTrailSteps = cs.solverState->Trail.size();
// Roll back changes to the constraint system.
cs.solverState->Trail.undo(startTrailSteps);
// Update statistics.
cs.solverState->endScope(scopeNumber,
startTrailSteps,
endTrailSteps);
// Clear out other "failed" state.
cs.failedConstraint = nullptr;
}
unsigned ConstraintSystem::SolverState::beginScope() {
++depth;
maxDepth = std::max(maxDepth, depth);
CS.incrementScopeCounter();
return NumSolverScopes++;
}
/// Update statistics when a scope ends.
void ConstraintSystem::SolverState::endScope(unsigned scopeNumber,
uint64_t startTrailSteps,
uint64_t endTrailSteps) {
ASSERT(depth > 0);
--depth;
NumTrailSteps += (endTrailSteps - startTrailSteps);
unsigned countSolverScopes = NumSolverScopes - scopeNumber;
if (countSolverScopes == 1)
CS.incrementLeafScopes();
}
/// Solve the system of constraints.
///
/// \param allowFreeTypeVariables How to bind free type variables in
/// the solution.
///
/// \returns a solution if a single unambiguous one could be found, or None if
/// ambiguous or unsolvable.
std::optional<Solution>
ConstraintSystem::solveSingle(FreeTypeVariableBinding allowFreeTypeVariables,
bool allowFixes) {
SolverState state(*this, allowFreeTypeVariables);
state.recordFixes = allowFixes;
SmallVector<Solution, 4> solutions;
solveImpl(solutions);
filterSolutions(solutions);
if (solutions.size() != 1)
return std::optional<Solution>();
return std::move(solutions[0]);
}
bool ConstraintSystem::Candidate::solve(
llvm::SmallSetVector<OverloadSetRefExpr *, 4> &shrunkExprs) {
// Don't attempt to solve candidate if there is closure
// expression involved, because it's handled specially
// by parent constraint system (e.g. parameter lists).
bool containsClosure = false;
E->forEachChildExpr([&](Expr *childExpr) -> Expr * {
if (isa<ClosureExpr>(childExpr)) {
containsClosure = true;
return nullptr;
}
return childExpr;
});
if (containsClosure)
return false;
auto cleanupImplicitExprs = [&](Expr *expr) {
expr->forEachChildExpr([&](Expr *childExpr) -> Expr * {
Type type = childExpr->getType();
if (childExpr->isImplicit() && type && type->hasTypeVariable())
childExpr->setType(Type());
return childExpr;
});
};
// Allocate new constraint system for sub-expression.
ConstraintSystem cs(DC, std::nullopt);
// Set up expression type checker timer for the candidate.
cs.startExpressionTimer(E);
// Generate constraints for the new system.
if (auto generatedExpr = cs.generateConstraints(E, DC)) {
E = generatedExpr;
} else {
// Failure to generate constraint system for sub-expression
// means we can't continue solving sub-expressions.
cleanupImplicitExprs(E);
return true;
}
// If this candidate is too complex given the number
// of the domains we have reduced so far, let's bail out early.
if (isTooComplexGiven(&cs, shrunkExprs))
return false;
auto &ctx = cs.getASTContext();
if (cs.isDebugMode()) {
auto &log = llvm::errs();
auto indent = cs.solverState ? cs.solverState->getCurrentIndent() : 0;
log.indent(indent) << "--- Solving candidate for shrinking at ";
auto R = E->getSourceRange();
if (R.isValid()) {
R.print(log, ctx.SourceMgr, /*PrintText=*/ false);
} else {
log << "<invalid range>";
}
log << " ---\n";
E->dump(log, indent);
log << '\n';
cs.print(log);
}
// If there is contextual type present, add an explicit "conversion"
// constraint to the system.
if (!CT.isNull()) {
auto constraintKind = ConstraintKind::Conversion;
if (CTP == CTP_CallArgument)
constraintKind = ConstraintKind::ArgumentConversion;
if (!CT->hasUnboundGenericType()) {
cs.addConstraint(constraintKind, cs.getType(E), CT,
cs.getConstraintLocator(E), /*isFavored=*/true);
}
}
// Try to solve the system and record all available solutions.
llvm::SmallVector<Solution, 2> solutions;
{
SolverState state(cs, FreeTypeVariableBinding::Allow);
// Use solve which doesn't try to filter solution list.
// Because we want the whole set of possible domain choices.
cs.solveImpl(solutions);
}
if (cs.isDebugMode()) {
auto &log = llvm::errs();
auto indent = cs.solverState ? cs.solverState->getCurrentIndent() : 0;
if (solutions.empty()) {
log << "\n";
log.indent(indent) << "--- No Solutions ---\n";
} else {
log << "\n";
log.indent(indent) << "--- Solutions ---\n";
for (unsigned i = 0, n = solutions.size(); i != n; ++i) {
auto &solution = solutions[i];
log << "\n";
log.indent(indent) << "--- Solution #" << i << " ---\n";
solution.dump(log, indent);
}
}
}
// Record found solutions as suggestions.
this->applySolutions(solutions, shrunkExprs);
// Let's double-check if we have any implicit expressions
// with type variables and nullify their types.
cleanupImplicitExprs(E);
// No solutions for the sub-expression means that either main expression
// needs salvaging or it's inconsistent (read: doesn't have solutions).
return solutions.empty();
}
void ConstraintSystem::Candidate::applySolutions(
llvm::SmallVectorImpl<Solution> &solutions,
llvm::SmallSetVector<OverloadSetRefExpr *, 4> &shrunkExprs) const {
// A collection of OSRs with their newly reduced domains,
// it's domains are sets because multiple solutions can have the same
// choice for one of the type variables, and we want no duplication.
llvm::SmallDenseMap<OverloadSetRefExpr *, llvm::SmallSetVector<ValueDecl *, 2>>
domains;
for (auto &solution : solutions) {
auto &score = solution.getFixedScore();
// Avoid any solutions with implicit value conversions
// because they might get reverted later when more context
// becomes available.
if (score.Data[SK_ImplicitValueConversion] > 0)
continue;
for (auto choice : solution.overloadChoices) {
// Some of the choices might not have locators.
if (!choice.getFirst())
continue;
auto anchor = choice.getFirst()->getAnchor();
auto *OSR = getAsExpr<OverloadSetRefExpr>(anchor);
// Anchor is not available or expression is not an overload set.
if (!OSR)
continue;
auto overload = choice.getSecond().choice;
auto type = overload.getDecl()->getInterfaceType();
// One of the solutions has polymorphic type associated with one of its
// type variables. Such functions can only be properly resolved
// via complete expression, so we'll have to forget solutions
// we have already recorded. They might not include all viable overload
// choices.
if (type->is<GenericFunctionType>()) {
return;
}
domains[OSR].insert(overload.getDecl());
}
}
// Reduce the domains.
for (auto &domain : domains) {
auto OSR = domain.getFirst();
auto &choices = domain.getSecond();
// If the domain wasn't reduced, skip it.
if (OSR->getDecls().size() == choices.size()) continue;
// Update the expression with the reduced domain.
MutableArrayRef<ValueDecl *> decls(
Allocator.Allocate<ValueDecl *>(choices.size()),
choices.size());
std::uninitialized_copy(choices.begin(), choices.end(), decls.begin());
OSR->setDecls(decls);
// Record successfully shrunk expression.
shrunkExprs.insert(OSR);
}
}
void ConstraintSystem::shrink(Expr *expr) {
if (getASTContext().TypeCheckerOpts.SolverDisableShrink)
return;
using DomainMap = llvm::SmallDenseMap<Expr *, ArrayRef<ValueDecl *>>;
// A collection of original domains of all of the expressions,
// so they can be restored in case of failure.
DomainMap domains;
struct ExprCollector : public ASTWalker {
Expr *PrimaryExpr;
// The primary constraint system.
ConstraintSystem &CS;