-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSILGenFunction.cpp
1944 lines (1691 loc) · 76.9 KB
/
SILGenFunction.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
//===--- SILGenFunction.cpp - Top-level lowering for functions ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines the primary routines for creating and emitting
// functions.
//
//===----------------------------------------------------------------------===//
#include "SILGenFunction.h"
#include "Cleanup.h"
#include "RValue.h"
#include "SILGenFunctionBuilder.h"
#include "Scope.h"
#include "swift/ABI/MetadataValues.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/ASTScope.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/FileUnit.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/ImportCache.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILProfiler.h"
#include "swift/SIL/SILUndef.h"
using namespace swift;
using namespace Lowering;
#define DEBUG_TYPE "silscopes"
//===----------------------------------------------------------------------===//
// SILGenFunction Class implementation
//===----------------------------------------------------------------------===//
SILGenFunction::SILGenFunction(SILGenModule &SGM, SILFunction &F,
DeclContext *DC, bool IsEmittingTopLevelCode)
: SGM(SGM), F(F), silConv(SGM.M), FunctionDC(DC),
StartOfPostmatter(F.end()), B(*this),
SF(DC ? DC->getParentSourceFile() : nullptr), Cleanups(*this),
StatsTracer(SGM.M.getASTContext().Stats, "SILGen-function", &F),
IsEmittingTopLevelCode(IsEmittingTopLevelCode) {
assert(DC && "creating SGF without a DeclContext?");
B.setInsertionPoint(createBasicBlock());
B.setCurrentDebugScope(F.getDebugScope());
// Populate VarDeclScopeMap.
SourceLoc SLoc = F.getLocation().getSourceLoc();
if (SF && SLoc) {
FnASTScope = ast_scope::ASTScopeImpl::findStartingScopeForLookup(SF, SLoc);
ScopeMap.insert({{FnASTScope, nullptr}, F.getDebugScope()});
// Collect all variable declarations in this scope.
struct Consumer : public namelookup::AbstractASTScopeDeclConsumer {
const ast_scope::ASTScopeImpl *ASTScope;
VarDeclScopeMapTy &VarDeclScopeMap;
Consumer(const ast_scope::ASTScopeImpl *ASTScope,
VarDeclScopeMapTy &VarDeclScopeMap)
: ASTScope(ASTScope), VarDeclScopeMap(VarDeclScopeMap) {}
bool consume(ArrayRef<ValueDecl *> values,
NullablePtr<DeclContext> baseDC) override {
LLVM_DEBUG(ASTScope->print(llvm::errs(), 0, false, false));
for (auto &value : values) {
LLVM_DEBUG({
if (value->hasName())
llvm::dbgs() << "+ " << value->getBaseIdentifier() << "\n";
});
// FIXME: ASTs coming out of the autodiff transformation trigger this.
// assert((VarDeclScopeMap.count(value) == 0 ||
// VarDeclScopeMap[value] == ASTScope) &&
// "VarDecl appears twice");
VarDeclScopeMap.insert({value, ASTScope});
}
return false;
}
bool lookInMembers(const DeclContext *) const override { return false; }
#ifndef NDEBUG
void startingNextLookupStep() override {}
void finishingLookup(std::string) const override {}
bool isTargetLookup() const override { return false; }
#endif
};
const_cast<ast_scope::ASTScopeImpl *>(FnASTScope)
->preOrderChildrenDo([&](ast_scope::ASTScopeImpl *ASTScope) {
if (!ASTScope->ignoreInDebugInfo()) {
Consumer consumer(ASTScope, VarDeclScopeMap);
ASTScope->lookupLocalsOrMembers(consumer);
}
});
}
}
/// SILGenFunction destructor - called after the entire function's AST has been
/// visited. This handles "falling off the end of the function" logic.
SILGenFunction::~SILGenFunction() {
// If the end of the function isn't terminated, we screwed up somewhere.
assert(!B.hasValidInsertionPoint() &&
"SILGenFunction did not terminate function?!");
// If we didn't clean up the rethrow destination, we screwed up somewhere.
assert(!ThrowDest.isValid() &&
"SILGenFunction did not emit throw destination");
}
//===----------------------------------------------------------------------===//
// Function emission
//===----------------------------------------------------------------------===//
// Get the #function name for a declaration.
DeclName SILGenModule::getMagicFunctionName(DeclContext *dc) {
// For closures, use the parent name.
if (auto closure = dyn_cast<AbstractClosureExpr>(dc)) {
return getMagicFunctionName(closure->getParent());
}
if (auto absFunc = dyn_cast<AbstractFunctionDecl>(dc)) {
// If this is an accessor, use the name of the storage.
if (auto accessor = dyn_cast<AccessorDecl>(absFunc))
return accessor->getStorage()->getName();
if (auto func = dyn_cast<FuncDecl>(absFunc)) {
// If this is a defer body, use the parent name.
if (func->isDeferBody()) {
return getMagicFunctionName(func->getParent());
}
}
return absFunc->getName();
}
if (auto init = dyn_cast<Initializer>(dc)) {
return getMagicFunctionName(init->getParent());
}
if (auto nominal = dyn_cast<NominalTypeDecl>(dc)) {
return nominal->getName();
}
if (auto tl = dyn_cast<TopLevelCodeDecl>(dc)) {
return tl->getModuleContext()->getName();
}
if (auto fu = dyn_cast<FileUnit>(dc)) {
return fu->getParentModule()->getName();
}
if (auto m = dyn_cast<ModuleDecl>(dc)) {
return m->getName();
}
if (auto e = dyn_cast<ExtensionDecl>(dc)) {
assert(e->getExtendedNominal() && "extension for nonnominal");
return e->getExtendedNominal()->getName();
}
if (auto EED = dyn_cast<EnumElementDecl>(dc)) {
return EED->getName();
}
if (auto SD = dyn_cast<SubscriptDecl>(dc)) {
return SD->getName();
}
llvm_unreachable("unexpected #function context");
}
DeclName SILGenModule::getMagicFunctionName(SILDeclRef ref) {
switch (ref.kind) {
case SILDeclRef::Kind::Func:
if (auto closure = ref.getAbstractClosureExpr())
return getMagicFunctionName(closure);
return getMagicFunctionName(cast<FuncDecl>(ref.getDecl()));
case SILDeclRef::Kind::Initializer:
case SILDeclRef::Kind::Allocator:
return getMagicFunctionName(cast<ConstructorDecl>(ref.getDecl()));
case SILDeclRef::Kind::Deallocator:
case SILDeclRef::Kind::IsolatedDeallocator:
case SILDeclRef::Kind::Destroyer:
return getMagicFunctionName(cast<DestructorDecl>(ref.getDecl()));
case SILDeclRef::Kind::GlobalAccessor:
return getMagicFunctionName(cast<VarDecl>(ref.getDecl())->getDeclContext());
case SILDeclRef::Kind::DefaultArgGenerator:
return getMagicFunctionName(cast<DeclContext>(ref.getDecl()));
case SILDeclRef::Kind::StoredPropertyInitializer:
case SILDeclRef::Kind::PropertyWrapperBackingInitializer:
return getMagicFunctionName(cast<VarDecl>(ref.getDecl())->getDeclContext());
case SILDeclRef::Kind::PropertyWrapperInitFromProjectedValue:
return getMagicFunctionName(cast<VarDecl>(ref.getDecl())->getDeclContext());
case SILDeclRef::Kind::IVarInitializer:
return getMagicFunctionName(cast<ClassDecl>(ref.getDecl()));
case SILDeclRef::Kind::IVarDestroyer:
return getMagicFunctionName(cast<ClassDecl>(ref.getDecl()));
case SILDeclRef::Kind::EnumElement:
return getMagicFunctionName(cast<EnumElementDecl>(ref.getDecl())
->getDeclContext());
case SILDeclRef::Kind::AsyncEntryPoint:
case SILDeclRef::Kind::EntryPoint: {
auto *file = ref.getDecl()->getDeclContext()->getParentSourceFile();
return getMagicFunctionName(file);
}
}
llvm_unreachable("Unhandled SILDeclRefKind in switch.");
}
bool SILGenFunction::referenceAllowed(ValueDecl *decl) {
// Use in any non-fragile functions.
if (FunctionDC->getResilienceExpansion() == ResilienceExpansion::Maximal)
return true;
// Allow same-module references.
auto *targetMod = decl->getDeclContext()->getParentModule();
auto *thisMod = FunctionDC->getParentModule();
if (thisMod == targetMod)
return true;
ModuleDecl::ImportFilter filter = {
ModuleDecl::ImportFilterKind::Exported,
ModuleDecl::ImportFilterKind::Default,
ModuleDecl::ImportFilterKind::SPIOnly};
if (thisMod->getResilienceStrategy() != ResilienceStrategy::Resilient)
filter |= ModuleDecl::ImportFilterKind::InternalOrBelow;
// Look through public module local imports and their reexports.
llvm::SmallVector<ImportedModule, 8> imports;
thisMod->getImportedModules(imports, filter);
auto &importCache = getASTContext().getImportCache();
for (auto &import : imports) {
if (importCache.isImportedBy(targetMod, import.importedModule))
return true;
}
return false;
}
SILDebugLocation SILGenFunction::getSILDebugLocation(
SILBuilder &B, SILLocation Loc,
std::optional<SILLocation> CurDebugLocOverride, bool ForMetaInstruction) {
const SILDebugScope *Scope = B.getCurrentDebugScope();
if (!Scope)
Scope = F.getDebugScope();
if (auto *SILScope = getScopeOrNull(Loc, ForMetaInstruction)) {
Scope = SILScope;
// Metainstructions such as a debug_value may break the flow of scopes and
// should not change the state of the builder.
if (!ForMetaInstruction)
B.setCurrentDebugScope(Scope);
}
auto overriddenLoc = CurDebugLocOverride ? *CurDebugLocOverride : Loc;
return SILDebugLocation(overriddenLoc, Scope);
}
const SILDebugScope *SILGenFunction::getScopeOrNull(SILLocation Loc,
bool ForMetaInstruction) {
if (!ForMetaInstruction) {
if (Loc.getKind() == SILLocation::CleanupKind ||
Loc.getKind() == SILLocation::ImplicitReturnKind ||
// The source locations produced by the ResultBuilder transformation are
// all over the place.
Loc.isImplicit() || Loc.isAutoGenerated())
return nullptr;
}
SourceLoc SLoc = Loc.getSourceLoc();
if (!SF || LastSourceLoc == SLoc)
return nullptr;
if (ForMetaInstruction)
if (ValueDecl *ValDecl = Loc.getAsASTNode<ValueDecl>()) {
// The source location of a VarDecl isn't necessarily in the same scope
// that the variable resides in for name lookup purposes.
auto ValueScope = VarDeclScopeMap.find(ValDecl);
if (ValueScope != VarDeclScopeMap.end())
return getOrCreateScope(ValueScope->second, F.getDebugScope());
}
return getOrCreateScope(SLoc);
}
const SILDebugScope *SILGenFunction::getOrCreateScope(SourceLoc SLoc) {
if (const SILDebugScope *macroScope = getMacroScope(SLoc))
return macroScope;
auto *astScope =
ast_scope::ASTScopeImpl::findStartingScopeForLookup(SF, SLoc);
// At the call site of a closure, the ASTScope created for the ClosureExpr
// has no parents, so filter it out here.
if (!astScope->getParent())
return nullptr;
const SILDebugScope *Scope = getOrCreateScope(astScope, F.getDebugScope());
assert(Scope && "failed to construct SILDebugScope from ASTScope");
return Scope;
}
namespace {
struct MacroInfo {
MacroInfo(SourceLoc SLoc, SourceLoc ExpansionSLoc)
: SLoc(SLoc), ExpansionSLoc(ExpansionSLoc) {}
SourceLoc SLoc;
SourceLoc ExpansionSLoc;
RegularLocation ExpansionLoc = RegularLocation((Decl*)nullptr);
std::string Name = "__unknown_macro__";
bool Freestanding = false;
};
}
static DeclContext *getInnermostFunctionContext(DeclContext *DC) {
for (; DC; DC = DC->getParent())
if (DC->getContextKind() == DeclContextKind::AbstractFunctionDecl)
return DC;
return nullptr;
}
/// Return location of the macro expansion and the macro name.
static MacroInfo getMacroInfo(const GeneratedSourceInfo &Info,
DeclContext *FunctionDC) {
MacroInfo Result(Info.generatedSourceRange.getStart(),
Info.originalSourceRange.getStart());
if (!Info.astNode)
return Result;
// Keep this in sync with ASTMangler::appendMacroExpansionContext().
Mangle::ASTMangler mangler(FunctionDC->getASTContext());
switch (Info.kind) {
case GeneratedSourceInfo::ExpressionMacroExpansion: {
auto parent = ASTNode::getFromOpaqueValue(Info.astNode);
if (auto expr =
cast_or_null<MacroExpansionExpr>(parent.dyn_cast<Expr *>())) {
Result.ExpansionLoc = RegularLocation(expr);
Result.Name = mangler.mangleMacroExpansion(expr);
} else {
auto decl = cast<MacroExpansionDecl>(parent.get<Decl *>());
Result.ExpansionLoc = RegularLocation(decl);
Result.Name = mangler.mangleMacroExpansion(decl);
}
// If the parent function of the macro expansion expression is not the
// current function, then the macro expanded to a closure or nested
// function. As far as the generated SIL is concerned this is the same as a
// function generated from a freestanding macro expansion.
DeclContext *MacroContext = getInnermostFunctionContext(Info.declContext);
if (MacroContext != FunctionDC)
Result.Freestanding = true;
break;
}
case GeneratedSourceInfo::DeclarationMacroExpansion:
case GeneratedSourceInfo::CodeItemMacroExpansion: {
auto expansion = cast<MacroExpansionDecl>(
ASTNode::getFromOpaqueValue(Info.astNode).get<Decl *>());
Result.ExpansionLoc = RegularLocation(expansion);
Result.Name = mangler.mangleMacroExpansion(expansion);
Result.Freestanding = true;
break;
}
#define FREESTANDING_MACRO_EXPANSION(Name, Description)
#define ATTACHED
case GeneratedSourceInfo::AccessorMacroExpansion:
case GeneratedSourceInfo::MemberAttributeMacroExpansion:
case GeneratedSourceInfo::MemberMacroExpansion:
case GeneratedSourceInfo::PeerMacroExpansion:
case GeneratedSourceInfo::ConformanceMacroExpansion:
case GeneratedSourceInfo::ExtensionMacroExpansion:
case GeneratedSourceInfo::PreambleMacroExpansion:
case GeneratedSourceInfo::BodyMacroExpansion: {
auto decl = ASTNode::getFromOpaqueValue(Info.astNode).get<Decl *>();
auto attr = Info.attachedMacroCustomAttr;
if (auto *macroDecl = decl->getResolvedMacro(attr)) {
Result.ExpansionLoc = RegularLocation(macroDecl);
Result.Name = macroDecl->getBaseName().userFacingName();
Result.Freestanding = true;
}
break;
}
case GeneratedSourceInfo::PrettyPrinted:
case GeneratedSourceInfo::ReplacedFunctionBody:
case GeneratedSourceInfo::DefaultArgument:
case GeneratedSourceInfo::AttributeFromClang:
break;
}
return Result;
}
const SILDebugScope *SILGenFunction::getMacroScope(SourceLoc SLoc) {
auto &SM = getSourceManager();
unsigned BufferID = SM.findBufferContainingLoc(SLoc);
auto GeneratedSourceInfo = SM.getGeneratedSourceInfo(BufferID);
if (!GeneratedSourceInfo)
return nullptr;
// There is no good way to represent freestanding macros as inlined functions,
// because entire function would need to be "inlined" into a top-level
// declaration that isn't part of a real function. By not handling them here,
// source locations will still point into the macro expansion buffer, but
// debug info doesn't know what macro that buffer was expanded from.
auto Macro = getMacroInfo(*GeneratedSourceInfo, FunctionDC);
if (Macro.Freestanding)
return nullptr;
const SILDebugScope *TopLevelScope;
auto It = InlinedScopeMap.find(BufferID);
if (It != InlinedScopeMap.end())
TopLevelScope = It->second;
else {
// Recursively create one inlined function + scope per layer of generated
// sources. Chains of Macro expansions are represented as flat
// function-level scopes.
SILGenFunctionBuilder B(SGM);
auto &ASTContext = SGM.M.getASTContext();
auto ExtInfo = SILFunctionType::ExtInfo::getThin();
auto FunctionType =
SILFunctionType::get(nullptr, ExtInfo, SILCoroutineKind::None,
ParameterConvention::Direct_Unowned, /*Params*/ {},
/*yields*/
{},
/*Results*/ {}, std::nullopt, SubstitutionMap(),
SubstitutionMap(), ASTContext);
StringRef MacroName = ASTContext.getIdentifier(Macro.Name).str();
RegularLocation MacroLoc(Macro.SLoc);
// Use the ExpansionLoc as the location so IRGenDebugInfo can extract the
// human-readable macro name from the MacroExpansionDecl.
SILFunction *MacroFn = B.getOrCreateFunction(
Macro.ExpansionLoc, MacroName,
SILLinkage::DefaultForDeclaration, FunctionType, IsNotBare,
IsNotTransparent, IsNotSerialized, IsNotDynamic, IsNotDistributed,
IsNotRuntimeAccessible);
// At the end of the chain ExpansionLoc should be a macro expansion node.
const SILDebugScope *InlinedAt = nullptr;
const SILDebugScope *ExpansionScope = getOrCreateScope(Macro.ExpansionSLoc);
// Inject an extra scope to hold the inlined call site.
if (ExpansionScope)
InlinedAt = new (SGM.M)
SILDebugScope(Macro.ExpansionLoc, nullptr, ExpansionScope,
ExpansionScope->InlinedCallSite);
TopLevelScope =
new (SGM.M) SILDebugScope(MacroLoc, MacroFn, nullptr, InlinedAt);
InlinedScopeMap.insert({BufferID, TopLevelScope});
}
// Create the scope hierarchy inside the macro expansion.
auto *MacroAstScope =
ast_scope::ASTScopeImpl::findStartingScopeForLookup(SF, Macro.SLoc);
return getOrCreateScope(MacroAstScope, TopLevelScope,
TopLevelScope->InlinedCallSite);
}
const SILDebugScope *
SILGenFunction::getOrCreateScope(const ast_scope::ASTScopeImpl *ASTScope,
const SILDebugScope *FnScope,
const SILDebugScope *InlinedAt) {
if (!ASTScope)
return FnScope;
// Top-level function scope?
if (ASTScope == FnASTScope)
return FnScope;
auto It = ScopeMap.find({ASTScope, InlinedAt});
if (It != ScopeMap.end())
return It->second;
LLVM_DEBUG(ASTScope->print(llvm::errs(), 0, false, false));
auto cache = [&](const SILDebugScope *SILScope) {
ScopeMap.insert({{ASTScope, InlinedAt}, SILScope});
assert(SILScope->getParentFunction() == &F &&
"inlinedAt points to other function");
return SILScope;
};
// Decide whether to pick a parent scope instead.
if (ASTScope->ignoreInDebugInfo()) {
LLVM_DEBUG(llvm::dbgs() << "ignored\n");
auto *ParentScope = getOrCreateScope(ASTScope->getParent().getPtrOrNull(),
FnScope, InlinedAt);
return ParentScope->InlinedCallSite != InlinedAt ? FnScope : ParentScope;
}
// Collapse BraceStmtScopes whose parent is a .*BodyScope.
if (auto Parent = ASTScope->getParent().getPtrOrNull())
if (Parent->getSourceRangeOfThisASTNode() ==
ASTScope->getSourceRangeOfThisASTNode())
return cache(getOrCreateScope(Parent, FnScope, InlinedAt));
// The calls to defer closures have cleanup source locations pointing to the
// defer. Reparent them into the current debug scope.
auto *AncestorScope = ASTScope->getParent().getPtrOrNull();
while (AncestorScope && AncestorScope != FnASTScope &&
!ScopeMap.count({AncestorScope, InlinedAt})) {
if (auto *FD = dyn_cast_or_null<FuncDecl>(
AncestorScope->getDeclIfAny().getPtrOrNull())) {
if (cast<DeclContext>(FD) != FunctionDC)
return cache(B.getCurrentDebugScope());
// This is this function's own scope.
// If this is the outermost BraceStmt scope, ignore it.
if (AncestorScope == ASTScope->getParent().getPtrOrNull())
return cache(FnScope);
break;
}
AncestorScope = AncestorScope->getParent().getPtrOrNull();
};
// Create the scope and recursively its parents. getLookupParent implements a
// special case for GuardBlockStmt, which is nested incorrectly.
auto *ParentScope = ASTScope->getLookupParent().getPtrOrNull();
const SILDebugScope *Parent =
getOrCreateScope(ParentScope, FnScope, InlinedAt);
SourceLoc SLoc = ASTScope->getSourceRangeOfThisASTNode().Start;
RegularLocation Loc(SLoc);
auto *SILScope = new (SGM.M)
SILDebugScope(Loc, FnScope->getParentFunction(), Parent, InlinedAt);
return cache(SILScope);
}
void SILGenFunction::enterDebugScope(SILLocation Loc, bool isBindingScope) {
// Initialize the builder with a default SILDebugScope for this scope.
if (const SILDebugScope *Scope = getScopeOrNull(Loc))
B.setCurrentDebugScope(Scope);
}
/// Return to the previous debug scope.
void SILGenFunction::leaveDebugScope() {}
std::tuple<ManagedValue, SILType>
SILGenFunction::emitSiblingMethodRef(SILLocation loc,
SILValue selfValue,
SILDeclRef methodConstant,
SubstitutionMap subMap) {
SILValue methodValue;
// If the method is dynamic, access it through runtime-hookable virtual
// dispatch (viz. objc_msgSend for now).
if (methodConstant.hasDecl()
&& methodConstant.getDecl()->shouldUseObjCDispatch()) {
methodValue =
emitDynamicMethodRef(
loc, methodConstant,
SGM.Types.getConstantInfo(getTypeExpansionContext(), methodConstant)
.SILFnType)
.getValue();
} else {
methodValue = emitGlobalFunctionRef(loc, methodConstant);
}
SILType methodTy = methodValue->getType();
// Specialize the generic method.
methodTy =
methodTy.substGenericArgs(SGM.M, subMap, getTypeExpansionContext());
return std::make_tuple(
ManagedValue::forObjectRValueWithoutOwnership(methodValue), methodTy);
}
void SILGenFunction::emitCaptures(SILLocation loc,
SILDeclRef closure,
CaptureEmission purpose,
SmallVectorImpl<ManagedValue> &capturedArgs) {
loc.markAutoGenerated();
auto captureInfo = SGM.Types.getLoweredLocalCaptures(closure);
// For boxed captures, we need to mark the contained variables as having
// escaped for DI diagnostics.
SmallVector<SILValue, 2> escapesToMark;
// Partial applications take ownership of the context parameters, so we'll
// need to pass ownership rather than merely guaranteeing parameters.
bool canGuarantee;
bool captureCanEscape = true;
switch (purpose) {
case CaptureEmission::PartialApplication:
canGuarantee = false;
break;
case CaptureEmission::ImmediateApplication:
canGuarantee = true;
break;
case CaptureEmission::AssignByWrapper:
canGuarantee = false;
captureCanEscape = false;
break;
}
auto expansion = getTypeExpansionContext();
for (auto capture : captureInfo.getCaptures()) {
if (capture.isDynamicSelfMetadata()) {
// The parameter type is the static Self type, but the value we
// want to pass is the dynamic Self type, so upcast it.
auto dynamicSelfMetatype = MetatypeType::get(
captureInfo.getDynamicSelfType());
SILType dynamicSILType = getLoweredType(dynamicSelfMetatype);
SILValue value = B.createMetatype(loc, dynamicSILType);
capturedArgs.push_back(
ManagedValue::forObjectRValueWithoutOwnership(value));
continue;
}
if (capture.isOpaqueValue() || capture.isPackElement()) {
capturedArgs.push_back(
emitRValueAsSingleValue(capture.getExpr()).ensurePlusOne(*this, loc));
continue;
}
auto *vd = cast<VarDecl>(capture.getDecl());
auto interfaceType = vd->getInterfaceType();
bool isPack = false;
if (interfaceType->is<PackExpansionType>()) {
assert(!vd->supportsMutation() &&
"Cannot capture a pack as an lvalue");
SmallVector<TupleTypeElt, 1> elts;
elts.push_back(interfaceType);
interfaceType = TupleType::get(elts, getASTContext());
isPack = true;
}
auto type = FunctionDC->mapTypeIntoContext(interfaceType);
auto valueType = FunctionDC->mapTypeIntoContext(
interfaceType->getReferenceStorageReferent());
//
// If we haven't emitted the captured value yet, we're forming a closure
// to a local function before all of its captures have been emitted. Eg,
//
// func f() { g() } // transitive capture of 'x'
// f() // closure formed here
// var x = 123 // 'x' defined here
// func g() { print(x) } // 'x' captured here
//
auto found = VarLocs.find(vd);
if (found == VarLocs.end()) {
auto &Diags = getASTContext().Diags;
SourceLoc loc;
if (closure.kind == SILDeclRef::Kind::DefaultArgGenerator) {
auto *param = getParameterAt(closure.getDecl(),
closure.defaultArgIndex);
assert(param);
loc = param->getLoc();
} else {
auto f = *closure.getAnyFunctionRef();
loc = f.getLoc();
}
Diags.diagnose(loc, diag::capture_before_declaration,
vd->getBaseIdentifier());
Diags.diagnose(vd->getLoc(), diag::captured_value_declared_here);
Diags.diagnose(capture.getLoc(), diag::value_captured_here);
// Emit an 'undef' of the correct type.
auto captureKind = SGM.Types.getDeclCaptureKind(capture, expansion);
switch (captureKind) {
case CaptureKind::Constant:
capturedArgs.push_back(emitUndef(getLoweredType(type)));
break;
case CaptureKind::Immutable:
case CaptureKind::StorageAddress: {
auto ty = getLoweredType(type);
if (SGM.M.useLoweredAddresses())
ty = ty.getAddressType();
capturedArgs.push_back(emitUndef(ty));
break;
}
case CaptureKind::ImmutableBox:
case CaptureKind::Box: {
bool isMutable = captureKind == CaptureKind::Box;
auto boxTy = SGM.Types.getContextBoxTypeForCapture(
vd,
SGM.Types.getLoweredRValueType(TypeExpansionContext::minimal(),
type),
FunctionDC->getGenericEnvironmentOfContext(),
/*mutable*/ isMutable);
capturedArgs.push_back(emitUndef(boxTy));
break;
}
}
continue;
}
// Get an address value for a SILValue if it is address only in an type
// expansion context without opaque archetype substitution.
auto getAddressValue = [&](SILValue entryValue, bool forceCopy,
bool forLValue) -> SILValue {
if (!SGM.M.useLoweredAddresses() && !forLValue && !isPack) {
// In opaque values mode, addresses aren't used except by lvalues.
auto &lowering = getTypeLowering(entryValue->getType());
if (entryValue->getType().isAddress()) {
// If the value is currently an address, load it, copying if needed.
if (lowering.isTrivial()) {
SILValue result = lowering.emitLoad(
B, loc, entryValue, LoadOwnershipQualifier::Trivial);
return result;
}
if (forceCopy) {
SILValue result =
lowering.emitLoadOfCopy(B, loc, entryValue, IsNotTake);
enterDestroyCleanup(result);
return result;
} else {
auto load = B.createLoadBorrow(
loc, ManagedValue::forBorrowedRValue(entryValue))
.getValue();
return load;
}
} else {
// Otherwise, just return it, copying if needed.
if (forceCopy && !lowering.isTrivial()) {
auto result = B.emitCopyValueOperation(loc, entryValue);
return result;
}
return entryValue;
}
} else if (SGM.M.useLoweredAddresses() &&
SGM.Types
.getTypeLowering(
valueType, TypeExpansionContext::
noOpaqueTypeArchetypesSubstitution(
expansion.getResilienceExpansion()))
.isAddressOnly() &&
!entryValue->getType().isAddress()) {
assert(!isPack);
auto addr = emitTemporaryAllocation(vd, entryValue->getType(),
DoesNotHaveDynamicLifetime,
IsNotLexical, IsNotFromVarDecl,
/*generateDebugInfo*/ false);
auto val = B.emitCopyValueOperation(loc, entryValue);
auto &lowering = getTypeLowering(entryValue->getType());
lowering.emitStore(B, loc, val, addr, StoreOwnershipQualifier::Init);
if (!forceCopy)
enterDestroyCleanup(addr);
return addr;
} else if (isPack) {
SILType ty = getLoweredType(valueType).getObjectType();
auto addr = B.createAllocStack(loc, ty);
enterDeallocStackCleanup(addr);
auto formalPackType = cast<TupleType>(valueType->getCanonicalType())
.getInducedPackType();
copyPackElementsToTuple(loc, addr, entryValue, formalPackType);
if (!forceCopy)
enterDestroyCleanup(addr);
return addr;
} else if (forceCopy) {
// We cannot pass a valid SILDebugVariable while creating the temp here
// See rdar://60425582
auto addr = B.createAllocStack(loc, entryValue->getType().getObjectType());
enterDeallocStackCleanup(addr);
B.createCopyAddr(loc, entryValue, addr, IsNotTake, IsInitialization);
return addr;
} else {
return entryValue;
}
};
auto &Entry = found->second;
auto val = Entry.value;
switch (SGM.Types.getDeclCaptureKind(capture, expansion)) {
case CaptureKind::Constant: {
assert(!isPack);
// let declarations.
auto &tl = getTypeLowering(valueType);
bool eliminateMoveOnlyWrapper =
val->getType().isMoveOnlyWrapped() &&
!interfaceType->is<SILMoveOnlyWrappedType>();
if (!val->getType().isAddress()) {
// Our 'let' binding can guarantee the lifetime for the callee,
// if we don't need to do anything more to it.
if (canGuarantee && !vd->getInterfaceType()->is<ReferenceStorageType>()) {
auto guaranteed = B.borrowObjectRValue(
*this, loc, val, ManagedValue::ScopeKind::Lexical);
if (eliminateMoveOnlyWrapper)
guaranteed = B.createGuaranteedMoveOnlyWrapperToCopyableValue(
loc, guaranteed);
capturedArgs.push_back(guaranteed);
break;
}
// Just copy a by-val let.
val = B.emitCopyValueOperation(loc, val);
// If we need to unwrap a moveonlywrapped value, do so now but in an
// owned way to ensure that the partial apply is viewed as a semantic
// use of the value.
if (eliminateMoveOnlyWrapper)
val = B.createOwnedMoveOnlyWrapperToCopyableValue(loc, val);
} else {
// If we have a mutable binding for a 'let', such as 'self' in an
// 'init' method, load it.
if (val->getType().isMoveOnly()) {
val = B.createMarkUnresolvedNonCopyableValueInst(
loc, val,
MarkUnresolvedNonCopyableValueInst::CheckKind::
NoConsumeOrAssign);
}
val = emitLoad(loc, val, tl, SGFContext(), IsNotTake).forward(*this);
}
// If we're capturing an unowned pointer by value, we will have just
// loaded it into a normal retained class pointer, but we capture it as
// an unowned pointer. Convert back now.
if (interfaceType->is<ReferenceStorageType>())
val = emitConversionFromSemanticValue(loc, val, getLoweredType(type));
capturedArgs.push_back(emitManagedRValueWithCleanup(val));
break;
}
case CaptureKind::Immutable: {
if (canGuarantee) {
// No-escaping stored declarations are captured as the
// address of the value.
auto addr =
getAddressValue(val, /*forceCopy=*/false, /*forLValue=*/false);
capturedArgs.push_back(
addr->getOwnershipKind() == OwnershipKind::Owned
? ManagedValue::forOwnedRValue(addr, CleanupHandle::invalid())
: ManagedValue::forBorrowedRValue(addr));
} else {
auto addr =
getAddressValue(val, /*forceCopy=*/true, /*forLValue=*/false);
if (!useLoweredAddresses()) {
auto &lowering = getTypeLowering(addr->getType());
auto rvalue =
lowering.isTrivial()
? ManagedValue::forObjectRValueWithoutOwnership(addr)
: ManagedValue::forOwnedRValue(addr,
CleanupHandle::invalid());
capturedArgs.push_back(rvalue);
break;
}
// If our address is move only wrapped, unwrap it.
if (addr->getType().isMoveOnlyWrapped()) {
addr = B.createMoveOnlyWrapperToCopyableAddr(loc, addr);
}
capturedArgs.push_back(ManagedValue::forOwnedAddressRValue(
addr, CleanupHandle::invalid()));
}
break;
}
case CaptureKind::StorageAddress: {
assert(!isPack);
auto addr = getAddressValue(val, /*forceCopy=*/false, /*forLValue=*/true);
// No-escaping stored declarations are captured as the
// address of the value.
assert(addr->getType().isAddress() && "no address for captured var!");
// If we have a moveonlywrapped address type, unwrap it.
if (addr->getType().isMoveOnlyWrapped())
addr = B.createMoveOnlyWrapperToCopyableAddr(loc, addr);
capturedArgs.push_back(ManagedValue::forLValue(addr));
break;
}
case CaptureKind::Box: {
assert(!isPack);
assert(val->getType().isAddress() &&
"no address for captured var!");
// Boxes of opaque return values stay opaque.
auto minimalLoweredType = SGM.Types.getLoweredRValueType(
TypeExpansionContext::minimal(), type->getCanonicalType());
// If this is a boxed variable, we can use it directly.
if (Entry.box &&
val->getType().getASTType() == minimalLoweredType) {
ManagedValue box;
// We can guarantee our own box to the callee.
if (canGuarantee) {
box = B.borrowObjectRValue(*this, loc, Entry.box,
ManagedValue::ScopeKind::Lexical);
} else {
box = B.copyOwnedObjectRValue(loc, Entry.box,
ManagedValue::ScopeKind::Lexical);
}
assert(box);
// If our captured value is a box with a moveonlywrapped type inside,
// unwrap it.
if (box.getType().isBoxedMoveOnlyWrappedType(&F)) {
CleanupCloner cloner(*this, box);
box = cloner.clone(
B.createMoveOnlyWrapperToCopyableBox(loc, box.forward(*this)));
}
capturedArgs.push_back(box);
if (captureCanEscape)
escapesToMark.push_back(val);
} else {
// Address only 'let' values are passed by box. This isn't great, in
// that a variable captured by multiple closures will be boxed for each
// one. This could be improved by doing an "isCaptured" analysis when
// emitting address-only let constants, and emit them into an alloc_box
// like a variable instead of into an alloc_stack.
//
// TODO: This might not be profitable anymore with guaranteed captures,
// since we could conceivably forward the copied value into the
// closure context and pass it down to the partially applied function
// in-place.
// TODO: Use immutable box for immutable captures.
auto boxTy = SGM.Types.getContextBoxTypeForCapture(
vd, minimalLoweredType,
FunctionDC->getGenericEnvironmentOfContext(),
/*mutable*/ true);
AllocBoxInst *allocBox = B.createAllocBox(loc, boxTy);
ProjectBoxInst *boxAddress = B.createProjectBox(loc, allocBox, 0);
B.createCopyAddr(loc, val, boxAddress, IsNotTake,
IsInitialization);
if (canGuarantee)
capturedArgs.push_back(
emitManagedRValueWithCleanup(allocBox).borrow(*this, loc));
else
capturedArgs.push_back(emitManagedRValueWithCleanup(allocBox));
}
break;
}
case CaptureKind::ImmutableBox: {
assert(!isPack);
assert(val->getType().isAddress() &&
"no address for captured var!");
// Boxes of opaque return values stay opaque.
auto minimalLoweredType = SGM.Types.getLoweredRValueType(
TypeExpansionContext::minimal(), type->getCanonicalType());
// If this is a boxed variable, we can use it directly.
if (Entry.box &&
val->getType().getASTType() == minimalLoweredType) {
// We can guarantee our own box to the callee.
if (canGuarantee) {
capturedArgs.push_back(B.borrowObjectRValue(
*this, loc, Entry.box, ManagedValue::ScopeKind::Lexical));
} else {
capturedArgs.push_back(emitManagedCopy(loc, Entry.box));
}
if (captureCanEscape)
escapesToMark.push_back(val);
} else {
// Address only 'let' values are passed by box. This isn't great, in
// that a variable captured by multiple closures will be boxed for each
// one. This could be improved by doing an "isCaptured" analysis when
// emitting address-only let constants, and emit them into an alloc_box
// like a variable instead of into an alloc_stack.
//
// TODO: This might not be profitable anymore with guaranteed captures,
// since we could conceivably forward the copied value into the
// closure context and pass it down to the partially applied function
// in-place.
// TODO: Use immutable box for immutable captures.
auto boxTy = SGM.Types.getContextBoxTypeForCapture(
vd, minimalLoweredType,
FunctionDC->getGenericEnvironmentOfContext(),
/*mutable*/ false);
AllocBoxInst *allocBox = B.createAllocBox(loc, boxTy);
ProjectBoxInst *boxAddress = B.createProjectBox(loc, allocBox, 0);
B.createCopyAddr(loc, val, boxAddress, IsNotTake,
IsInitialization);
if (canGuarantee)
capturedArgs.push_back(
emitManagedRValueWithCleanup(allocBox).borrow(*this, loc));
else
capturedArgs.push_back(emitManagedRValueWithCleanup(allocBox));
}
break;
}
}
}
// Mark box addresses as captured for DI purposes. The values must have
// been fully initialized before we close over them.
if (!escapesToMark.empty()) {
B.createMarkFunctionEscape(loc, escapesToMark);
}
}
ManagedValue