/
SILFunction.h
1676 lines (1351 loc) · 58.1 KB
/
SILFunction.h
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
//===--- SILFunction.h - Defines the SILFunction class ----------*- C++ -*-===//
//
// 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 SILFunction class.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_SIL_SILFUNCTION_H
#define SWIFT_SIL_SILFUNCTION_H
#include "swift/AST/ASTNode.h"
#include "swift/AST/Availability.h"
#include "swift/AST/Module.h"
#include "swift/AST/ResilienceExpansion.h"
#include "swift/Basic/ProfileCounter.h"
#include "swift/Basic/SwiftObjectHeader.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/SILDebugScope.h"
#include "swift/SIL/SILDeclRef.h"
#include "swift/SIL/SILLinkage.h"
#include "swift/SIL/SILPrintContext.h"
namespace swift {
class ASTContext;
class SILInstruction;
class SILModule;
class SILFunctionBuilder;
class SILProfiler;
class BasicBlockBitfield;
class NodeBitfield;
class OperandBitfield;
class CalleeCache;
class SILUndef;
namespace Lowering {
class TypeLowering;
class AbstractionPattern;
}
enum IsBare_t { IsNotBare, IsBare };
enum IsTransparent_t { IsNotTransparent, IsTransparent };
enum Inline_t { InlineDefault, NoInline, AlwaysInline };
enum IsThunk_t {
IsNotThunk,
IsThunk,
IsReabstractionThunk,
IsSignatureOptimizedThunk
};
enum IsDynamicallyReplaceable_t {
IsNotDynamic,
IsDynamic
};
enum IsExactSelfClass_t {
IsNotExactSelfClass,
IsExactSelfClass,
};
enum IsDistributed_t {
IsNotDistributed,
IsDistributed,
};
enum IsRuntimeAccessible_t {
IsNotRuntimeAccessible,
IsRuntimeAccessible
};
enum ForceEnableLexicalLifetimes_t {
DoNotForceEnableLexicalLifetimes,
DoForceEnableLexicalLifetimes
};
enum UseStackForPackMetadata_t {
DoNotUseStackForPackMetadata,
DoUseStackForPackMetadata,
};
enum class PerformanceConstraints : uint8_t {
None = 0,
NoAllocation = 1,
NoLocks = 2,
NoRuntime = 3,
NoExistentials = 4,
NoObjCBridging = 5
};
class SILSpecializeAttr final {
friend SILFunction;
public:
enum class SpecializationKind {
Full,
Partial
};
static GenericSignature buildTypeErasedSignature(
GenericSignature sig, ArrayRef<Type> typeErasedParams);
static SILSpecializeAttr *create(SILModule &M,
GenericSignature specializedSignature,
ArrayRef<Type> typeErasedParams,
bool exported, SpecializationKind kind,
SILFunction *target, Identifier spiGroup,
const ModuleDecl *spiModule,
AvailabilityContext availability);
bool isExported() const {
return exported;
}
bool isFullSpecialization() const {
return kind == SpecializationKind::Full;
}
bool isPartialSpecialization() const {
return kind == SpecializationKind::Partial;
}
SpecializationKind getSpecializationKind() const {
return kind;
}
GenericSignature getSpecializedSignature() const {
return specializedSignature;
}
GenericSignature getUnerasedSpecializedSignature() const {
return unerasedSpecializedSignature;
}
ArrayRef<Type> getTypeErasedParams() const {
return typeErasedParams;
}
SILFunction *getFunction() const {
return F;
}
SILFunction *getTargetFunction() const {
return targetFunction;
}
Identifier getSPIGroup() const {
return spiGroup;
}
const ModuleDecl *getSPIModule() const {
return spiModule;
}
AvailabilityContext getAvailability() const {
return availability;
}
void print(llvm::raw_ostream &OS) const;
private:
SpecializationKind kind;
bool exported;
GenericSignature specializedSignature;
GenericSignature unerasedSpecializedSignature;
llvm::SmallVector<Type, 2> typeErasedParams;
Identifier spiGroup;
AvailabilityContext availability;
const ModuleDecl *spiModule = nullptr;
SILFunction *F = nullptr;
SILFunction *targetFunction = nullptr;
SILSpecializeAttr(bool exported, SpecializationKind kind,
GenericSignature specializedSignature,
GenericSignature unerasedSpecializedSignature,
ArrayRef<Type> typeErasedParams,
SILFunction *target, Identifier spiGroup,
const ModuleDecl *spiModule,
AvailabilityContext availability);
};
/// SILFunction - A function body that has been lowered to SIL. This consists of
/// zero or more SIL SILBasicBlock objects that contain the SILInstruction
/// objects making up the function.
class SILFunction
: public llvm::ilist_node<SILFunction>, public SILAllocated<SILFunction>,
public SwiftObjectHeader {
private:
void *libswiftSpecificData[4];
public:
using BlockListType = llvm::iplist<SILBasicBlock>;
// For more information see docs/SIL.rst
enum class Purpose : uint8_t {
None,
GlobalInit,
GlobalInitOnceFunction,
LazyPropertyGetter
};
private:
friend class SILBasicBlock;
friend class SILModule;
friend class SILFunctionBuilder;
template <typename, unsigned> friend class BasicBlockData;
template <class, class> friend class SILBitfield;
friend class BasicBlockBitfield;
friend class NodeBitfield;
friend class OperandBitfield;
friend SILUndef;
/// Module - The SIL module that the function belongs to.
SILModule &Module;
/// The mangled name of the SIL function, which will be propagated
/// to the binary. A pointer into the module's lookup table.
StringRef Name;
/// A single-linked list of snapshots of the function.
///
/// Snapshots are copies of the current function at a given point in time.
SILFunction *snapshots = nullptr;
/// The snapshot ID of this function.
///
/// 0 means, it's not a snapshot, but the original function.
int snapshotID = 0;
/// The lowered type of the function.
CanSILFunctionType LoweredType;
/// The context archetypes of the function.
GenericEnvironment *GenericEnv = nullptr;
/// The information about specialization.
/// Only set if this function is a specialization of another function.
const GenericSpecializationInformation *SpecializationInfo = nullptr;
/// The forwarding substitution map, lazily computed.
SubstitutionMap ForwardingSubMap;
/// The collection of all BasicBlocks in the SILFunction. Empty for external
/// function references.
BlockListType BlockList;
/// The owning declaration of this function's clang node, if applicable.
ValueDecl *ClangNodeOwner = nullptr;
/// The source location and scope of the function.
const SILDebugScope *DebugScope = nullptr;
/// The AST decl context of the function.
DeclContext *DeclCtxt = nullptr;
/// The module that defines this function. This member should only be set as
/// a fallback when a \c DeclCtxt is unavailable.
ModuleDecl *ParentModule = nullptr;
/// The profiler for instrumentation based profiling, or null if profiling is
/// disabled.
SILProfiler *Profiler = nullptr;
/// The function this function is meant to replace. Null if this is not a
/// @_dynamicReplacement(for:) function.
SILFunction *ReplacedFunction = nullptr;
/// This SILFunction REFerences an ad-hoc protocol requirement witness in
/// order to keep it alive, such that it main be obtained in IRGen. Without
/// this explicit reference, the witness would seem not-used, and not be
/// accessible for IRGen.
///
/// Specifically, one such case is the DistributedTargetInvocationDecoder's
/// 'decodeNextArgument' which must be retained, as it is only used from IRGen
/// and such, appears as-if unused in SIL and would get optimized away.
// TODO: Consider making this a general "references adhoc functions" and make it an array?
SILFunction *RefAdHocRequirementFunction = nullptr;
Identifier ObjCReplacementFor;
/// The head of a single-linked list of currently alive BasicBlockBitfield.
BasicBlockBitfield *newestAliveBlockBitfield = nullptr;
/// The head of a single-linked list of currently alive NodeBitfield.
NodeBitfield *newestAliveNodeBitfield = nullptr;
/// The head of a single-linked list of currently alive OperandBitfields.
OperandBitfield *newestAliveOperandBitfield = nullptr;
/// A monotonically increasing ID which is incremented whenever a
/// BasicBlockBitfield, NodeBitfield, or OperandBitfield is constructed. For
/// details see SILBitfield::bitfieldID;
uint64_t currentBitfieldID = 1;
/// Unique identifier for vector indexing and deterministic sorting.
/// May be reused when zombie functions are recovered.
unsigned index;
/// The function's set of semantics attributes.
///
/// TODO: Why is this using a std::string? Why don't we use uniqued
/// StringRefs?
std::vector<std::string> SemanticsAttrSet;
/// The function's remaining set of specialize attributes.
std::vector<SILSpecializeAttr*> SpecializeAttrSet;
/// Name of a section if @_section attribute was used, otherwise empty.
StringRef Section;
/// Name of a Wasm export if @_expose(wasm) attribute was used, otherwise
/// empty.
StringRef WasmExportName;
/// Name of a Wasm import module and field if @_extern(wasm) attribute
std::optional<std::pair<StringRef, StringRef>> WasmImportModuleAndField;
/// Has value if there's a profile for this function
/// Contains Function Entry Count
ProfileCounter EntryCount;
/// The availability used to determine if declarations of this function
/// should use weak linking.
AvailabilityContext Availability;
Purpose specialPurpose = Purpose::None;
PerformanceConstraints perfConstraints = PerformanceConstraints::None;
/// This is the set of undef values we've created, for uniquing purposes.
///
/// We use a SmallDenseMap since in most functions, we will have only one type
/// of undef if we have any at all. In that case, by staying small we avoid
/// needing a heap allocation.
llvm::SmallDenseMap<SILType, SILUndef *, 1> undefValues;
/// This is the number of uses of this SILFunction inside the SIL.
/// It does not include references from debug scopes.
unsigned RefCount = 0;
/// Used to verify if a BasicBlockData is not valid anymore.
/// This counter is incremented every time a BasicBlockData re-assigns new
/// block indices.
unsigned BlockListChangeIdx = 0;
/// The isolation of this function.
std::optional<ActorIsolation> actorIsolation;
/// The function's bare attribute. Bare means that the function is SIL-only
/// and does not require debug info.
unsigned Bare : 1;
/// The function's transparent attribute.
unsigned Transparent : 1;
/// The function's serialized attribute.
bool Serialized : 1;
/// Specifies if this function is a thunk or a reabstraction thunk.
///
/// The inliner uses this information to avoid inlining (non-trivial)
/// functions into the thunk.
unsigned Thunk : 2;
/// The scope in which the parent class can be subclassed, if this is a method
/// which is contained in the vtable of that class.
unsigned ClassSubclassScope : 2;
/// The function's global_init attribute.
unsigned GlobalInitFlag : 1;
/// The function's noinline attribute.
unsigned InlineStrategy : 2;
/// The linkage of the function.
unsigned Linkage : NumSILLinkageBits;
/// Set if the function may be referenced from C code and should thus be
/// preserved and exported more widely than its Swift linkage and usage
/// would indicate.
unsigned HasCReferences : 1;
/// Whether attribute @_used was present
unsigned MarkedAsUsed : 1;
/// Whether cross-module references to this function should always use weak
/// linking.
unsigned IsAlwaysWeakImported : 1;
/// Whether the implementation can be dynamically replaced.
unsigned IsDynamicReplaceable : 1;
/// If true, this indicates that a class method implementation will always be
/// invoked with a `self` argument of the exact base class type.
unsigned ExactSelfClass : 1;
/// Check whether this is a distributed method.
unsigned IsDistributed : 1;
/// Check whether this function could be looked up at runtime via special API.
unsigned IsRuntimeAccessible : 1;
unsigned stackProtection : 1;
/// True if this function is inlined at least once. This means that the
/// debug info keeps a pointer to this function.
unsigned Inlined : 1;
/// True if this function is a zombie function. This means that the function
/// is dead and not referenced from anywhere inside the SIL. But it is kept
/// for other purposes:
/// *) It is inlined and the debug info keeps a reference to the function.
/// *) It is a dead method of a class which has higher visibility than the
/// method itself. In this case we need to create a vtable stub for it.
/// *) It is a function referenced by the specialization information.
unsigned Zombie : 1;
/// True if this function is in Ownership SSA form and thus must pass
/// ownership verification.
///
/// This enables the verifier to easily prove that before the Ownership Model
/// Eliminator runs on a function, we only see a non-semantic-arc world and
/// after the pass runs, we only see a semantic-arc world.
unsigned HasOwnership : 1;
/// Set if the function body was deserialized from canonical SIL. This implies
/// that the function's home module performed SIL diagnostics prior to
/// serialization.
unsigned WasDeserializedCanonical : 1;
/// True if this is a reabstraction thunk of escaping function type whose
/// single argument is a potentially non-escaping closure. This is an escape
/// hatch to allow non-escaping functions to be stored or passed as an
/// argument with escaping function type. The thunk argument's function type
/// is not necessarily @noescape. The only relevant aspect of the argument is
/// that it may have unboxed capture (i.e. @inout_aliasable parameters).
unsigned IsWithoutActuallyEscapingThunk : 1;
/// If != OptimizationMode::NotSet, the optimization mode specified with an
/// function attribute.
unsigned OptMode : NumOptimizationModeBits;
/// The function's effects attribute.
unsigned EffectsKindAttr : NumEffectsKindBits;
/// If true, the function has lexical lifetimes even if the module does not.
unsigned ForceEnableLexicalLifetimes : 1;
/// If true, the function contains an instruction that prevents stack nesting
/// from running with pack metadata markers in place.
unsigned UseStackForPackMetadata : 1;
/// If true, the function returns a non-escapable value without any
/// lifetime-dependence on an argument.
unsigned HasUnsafeNonEscapableResult : 1;
unsigned HasResultDependsOnSelf : 1;
/// True, if this function or a caller (transitively) has a performance
/// constraint.
/// If true, optimizations must not introduce new runtime calls or metadata
/// creation, which are not there after SILGen.
/// Note that this flag is not serialized, because it's computed locally
/// within a module by the MandatoryOptimizations pass.
unsigned IsPerformanceConstraint : 1;
static void
validateSubclassScope(SubclassScope scope, IsThunk_t isThunk,
const GenericSpecializationInformation *genericInfo) {
#ifndef NDEBUG
// The _original_ function for a method can turn into a thunk through
// signature optimization, meaning it needs to retain its subclassScope, but
// other thunks and specializations are implementation details and so
// shouldn't be connected to their parent class.
bool thunkCanHaveSubclassScope;
switch (isThunk) {
case IsNotThunk:
case IsSignatureOptimizedThunk:
thunkCanHaveSubclassScope = true;
break;
case IsThunk:
case IsReabstractionThunk:
thunkCanHaveSubclassScope = false;
break;
}
auto allowsInterestingScopes = thunkCanHaveSubclassScope && !genericInfo;
assert(
allowsInterestingScopes ||
scope == SubclassScope::NotApplicable &&
"SubclassScope on specialization or non-signature-optimized thunk");
#endif
}
SILFunction(SILModule &module, SILLinkage linkage, StringRef mangledName,
CanSILFunctionType loweredType, GenericEnvironment *genericEnv,
IsBare_t isBareSILFunction, IsTransparent_t isTrans,
IsSerialized_t isSerialized, ProfileCounter entryCount,
IsThunk_t isThunk, SubclassScope classSubclassScope,
Inline_t inlineStrategy, EffectsKind E,
const SILDebugScope *debugScope,
IsDynamicallyReplaceable_t isDynamic,
IsExactSelfClass_t isExactSelfClass,
IsDistributed_t isDistributed,
IsRuntimeAccessible_t isRuntimeAccessible);
static SILFunction *
create(SILModule &M, SILLinkage linkage, StringRef name,
CanSILFunctionType loweredType, GenericEnvironment *genericEnv,
std::optional<SILLocation> loc, IsBare_t isBareSILFunction,
IsTransparent_t isTrans, IsSerialized_t isSerialized,
ProfileCounter entryCount, IsDynamicallyReplaceable_t isDynamic,
IsDistributed_t isDistributed,
IsRuntimeAccessible_t isRuntimeAccessible,
IsExactSelfClass_t isExactSelfClass, IsThunk_t isThunk = IsNotThunk,
SubclassScope classSubclassScope = SubclassScope::NotApplicable,
Inline_t inlineStrategy = InlineDefault,
EffectsKind EffectsKindAttr = EffectsKind::Unspecified,
SILFunction *InsertBefore = nullptr,
const SILDebugScope *DebugScope = nullptr);
void init(SILLinkage Linkage, StringRef Name, CanSILFunctionType LoweredType,
GenericEnvironment *genericEnv, IsBare_t isBareSILFunction,
IsTransparent_t isTrans, IsSerialized_t isSerialized,
ProfileCounter entryCount, IsThunk_t isThunk,
SubclassScope classSubclassScope, Inline_t inlineStrategy,
EffectsKind E, const SILDebugScope *DebugScope,
IsDynamicallyReplaceable_t isDynamic,
IsExactSelfClass_t isExactSelfClass, IsDistributed_t isDistributed,
IsRuntimeAccessible_t isRuntimeAccessible);
/// Set has ownership to the given value. True means that the function has
/// ownership, false means it does not.
///
/// Only for use by FunctionBuilders!
void setHasOwnership(bool newValue) { HasOwnership = newValue; }
void setName(StringRef name) {
// All the snapshots share the same name.
SILFunction *sn = this;
do {
sn->Name = name;
} while ((sn = sn->snapshots) != nullptr);
}
public:
~SILFunction();
SILModule &getModule() const { return Module; }
/// Creates a snapshot with a given `ID` from the current function.
void createSnapshot(int ID);
/// Returns the snapshot with the given `ID` or null if no such snapshot exists.
SILFunction *getSnapshot(int ID);
/// Restores the current function from a given snapshot.
void restoreFromSnapshot(int ID);
/// Deletes a snapshot with the `ID`.
void deleteSnapshot(int ID);
SILType getLoweredType() const {
return SILType::getPrimitiveObjectType(LoweredType);
}
CanSILFunctionType getLoweredFunctionType() const {
return LoweredType;
}
CanSILFunctionType
getLoweredFunctionTypeInContext(TypeExpansionContext context) const;
SILType getLoweredTypeInContext(TypeExpansionContext context) const {
return SILType::getPrimitiveObjectType(
getLoweredFunctionTypeInContext(context));
}
SILFunctionConventions getConventions() const {
return SILFunctionConventions(LoweredType, getModule());
}
SILFunctionConventions getConventionsInContext() const {
auto fnType = getLoweredFunctionTypeInContext(getTypeExpansionContext());
return SILFunctionConventions(fnType, getModule());
}
unsigned getIndex() const { return index; }
SILProfiler *getProfiler() const { return Profiler; }
SILFunction *getDynamicallyReplacedFunction() const {
return ReplacedFunction;
}
void setDynamicallyReplacedFunction(SILFunction *f) {
assert(ReplacedFunction == nullptr && "already set");
assert(!hasObjCReplacement());
if (f == nullptr)
return;
ReplacedFunction = f;
ReplacedFunction->incrementRefCount();
}
/// This function should only be called when SILFunctions are bulk deleted.
void dropDynamicallyReplacedFunction() {
if (!ReplacedFunction)
return;
ReplacedFunction->decrementRefCount();
ReplacedFunction = nullptr;
}
SILFunction *getReferencedAdHocRequirementWitnessFunction() const {
return RefAdHocRequirementFunction;
}
// Marks that this `SILFunction` uses the passed in ad-hoc protocol
// requirement witness `f` and therefore must retain it explicitly,
// otherwise we might not be able to get a reference to it.
void setReferencedAdHocRequirementWitnessFunction(SILFunction *f) {
assert(RefAdHocRequirementFunction == nullptr && "already set");
if (f == nullptr)
return;
RefAdHocRequirementFunction = f;
RefAdHocRequirementFunction->incrementRefCount();
}
void dropReferencedAdHocRequirementWitnessFunction() {
if (!RefAdHocRequirementFunction)
return;
RefAdHocRequirementFunction->decrementRefCount();
RefAdHocRequirementFunction = nullptr;
}
bool hasObjCReplacement() const {
return !ObjCReplacementFor.empty();
}
Identifier getObjCReplacement() const {
return ObjCReplacementFor;
}
void setObjCReplacement(AbstractFunctionDecl *replacedDecl);
void setObjCReplacement(Identifier replacedDecl);
void setProfiler(SILProfiler *InheritedProfiler) {
assert(!Profiler && "Function already has a profiler");
Profiler = InheritedProfiler;
}
void createProfiler(SILDeclRef Ref);
ProfileCounter getEntryCount() const { return EntryCount; }
void setEntryCount(ProfileCounter Count) { EntryCount = Count; }
bool isNoReturnFunction(TypeExpansionContext context) const;
/// Unsafely rewrite the lowered type of this function.
///
/// This routine does not touch the entry block arguments
/// or return instructions; you need to do that yourself
/// if you care.
///
/// This routine does not update all the references in the module
/// You have to do that yourself
void rewriteLoweredTypeUnsafe(CanSILFunctionType newType) {
LoweredType = newType;
}
/// Return the number of entities referring to this function (other
/// than the SILModule).
unsigned getRefCount() const { return RefCount; }
/// Increment the reference count.
void incrementRefCount() {
RefCount++;
assert(RefCount != 0 && "Overflow of reference count!");
}
/// Decrement the reference count.
void decrementRefCount() {
assert(RefCount != 0 && "Expected non-zero reference count on decrement!");
RefCount--;
}
/// Drops all uses belonging to instructions in this function. The only valid
/// operation performable on this object after this is called is called the
/// destructor or deallocation.
void dropAllReferences() {
for (SILBasicBlock &BB : *this)
BB.dropAllReferences();
}
/// Notify that this function was inlined. This implies that it is still
/// needed for debug info generation, even if it is removed afterwards.
void setInlined() {
assert(!isZombie() && "Can't inline a zombie function");
Inlined = true;
}
/// Returns true if this function was inlined.
bool isInlined() const { return Inlined; }
/// Mark this function as removed from the module's function list, but kept
/// as "zombie" for debug info or vtable stub generation.
void setZombie() {
assert(!isZombie() && "Function is a zombie function already");
Zombie = true;
}
/// Returns true if this function is dead, but kept in the module's zombie list.
bool isZombie() const { return Zombie; }
/// Returns true if this function has qualified ownership instructions in it.
bool hasOwnership() const { return HasOwnership; }
/// Sets the HasOwnership flag to false. This signals to SIL that no
/// ownership instructions should be in this function any more.
void setOwnershipEliminated() { setHasOwnership(false); }
/// Returns true if this function was deserialized from canonical
/// SIL. (.swiftmodule files contain canonical SIL; .sib files may be 'raw'
/// SIL). If so, diagnostics should not be reapplied.
bool wasDeserializedCanonical() const { return WasDeserializedCanonical; }
void setWasDeserializedCanonical(bool val = true) {
WasDeserializedCanonical = val;
}
ForceEnableLexicalLifetimes_t forceEnableLexicalLifetimes() const {
return ForceEnableLexicalLifetimes_t(ForceEnableLexicalLifetimes);
}
void setForceEnableLexicalLifetimes(ForceEnableLexicalLifetimes_t value) {
ForceEnableLexicalLifetimes = value;
}
UseStackForPackMetadata_t useStackForPackMetadata() const {
return UseStackForPackMetadata_t(UseStackForPackMetadata);
}
void setUseStackForPackMetadata(UseStackForPackMetadata_t value) {
UseStackForPackMetadata = value;
}
bool hasUnsafeNonEscapableResult() const {
return HasUnsafeNonEscapableResult;
}
void setHasUnsafeNonEscapableResult(bool value) {
HasUnsafeNonEscapableResult = value;
}
bool hasResultDependsOnSelf() const { return HasResultDependsOnSelf; }
void setHasResultDependsOnSelf(bool flag = true) {
HasResultDependsOnSelf = flag;
}
/// Returns true if this is a reabstraction thunk of escaping function type
/// whose single argument is a potentially non-escaping closure. i.e. the
/// thunks' function argument may itself have @inout_aliasable parameters.
bool isWithoutActuallyEscapingThunk() const {
return IsWithoutActuallyEscapingThunk;
}
void setWithoutActuallyEscapingThunk(bool val = true) {
assert(!val || isThunk() == IsReabstractionThunk);
IsWithoutActuallyEscapingThunk = val;
}
bool isAsync() const { return LoweredType->isAsync(); }
/// Returns the calling convention used by this entry point.
SILFunctionTypeRepresentation getRepresentation() const {
return getLoweredFunctionType()->getRepresentation();
}
ResilienceExpansion getResilienceExpansion() const {
return (isSerialized()
? ResilienceExpansion::Minimal
: ResilienceExpansion::Maximal);
}
// Returns the type expansion context to be used inside this function.
TypeExpansionContext getTypeExpansionContext() const {
return TypeExpansionContext(*this);
}
const Lowering::TypeLowering &
getTypeLowering(Lowering::AbstractionPattern orig, Type subst);
const Lowering::TypeLowering &getTypeLowering(Type t) const;
SILType getLoweredType(Lowering::AbstractionPattern orig, Type subst) const;
SILType getLoweredType(Type t) const;
CanType getLoweredRValueType(Lowering::AbstractionPattern orig, Type subst) const;
CanType getLoweredRValueType(Type t) const;
SILType getLoweredLoadableType(Type t) const;
SILType getLoweredType(SILType t) const;
const Lowering::TypeLowering &getTypeLowering(SILType type) const;
bool isTypeABIAccessible(SILType type) const;
/// Returns true if this function has a calling convention that has a self
/// argument.
bool hasSelfParam() const {
return getLoweredFunctionType()->hasSelfParam();
}
/// Returns true if the function has parameters that are consumed by the
// callee.
bool hasOwnedParameters() const {
for (auto &ParamInfo : getLoweredFunctionType()->getParameters()) {
if (ParamInfo.isConsumed())
return true;
}
return false;
}
// Returns true if the function has indirect out parameters.
bool hasIndirectFormalResults() const {
return getLoweredFunctionType()->hasIndirectFormalResults();
}
// Returns true if the function has any generic arguments.
bool isGeneric() const {
auto s = getLoweredFunctionType()->getInvocationGenericSignature();
return s && !s->areAllParamsConcrete();
}
/// Returns true if this function ie either a class method, or a
/// closure that captures the 'self' value or its metatype.
///
/// If this returns true, DynamicSelfType can be used in the body
/// of the function.
///
/// Note that this is not the same as hasSelfParam().
///
/// For closures that capture DynamicSelfType, hasDynamicSelfMetadata()
/// is true and hasSelfParam() is false. For methods on value types,
/// hasSelfParam() is true and hasDynamicSelfMetadata() is false.
bool hasDynamicSelfMetadata() const;
/// Return the mangled name of this SILFunction.
StringRef getName() const { return Name; }
/// A convenience function which checks if the function has a specific
/// \p name. It is equivalent to getName() == Name, but as it is not
/// inlined it can be called from the debugger.
bool hasName(const char *Name) const;
/// True if this is a declaration of a function defined in another module.
bool isExternalDeclaration() const { return BlockList.empty(); }
/// Returns true if this is a definition of a function defined in this module.
bool isDefinition() const { return !isExternalDeclaration(); }
/// Returns true if there exist pre-specializations.
bool hasPrespecialization() const;
/// Get this function's linkage attribute.
SILLinkage getLinkage() const { return SILLinkage(Linkage); }
/// Set the function's linkage attribute.
void setLinkage(SILLinkage linkage) { Linkage = unsigned(linkage); }
/// Returns true if this function can be inlined into a fragile function
/// body.
bool hasValidLinkageForFragileInline() const { return isSerialized(); }
/// Returns true if this function can be referenced from a fragile function
/// body.
bool hasValidLinkageForFragileRef() const;
/// Get's the effective linkage which is used to derive the llvm linkage.
/// Usually this is the same as getLinkage(), except in one case: if this
/// function is a method in a class which has higher visibility than the
/// method itself, the function can be referenced from vtables of derived
/// classes in other compilation units.
SILLinkage getEffectiveSymbolLinkage() const {
return effectiveLinkageForClassMember(getLinkage(),
getClassSubclassScope());
}
/// Helper method which returns true if this function has "external" linkage.
bool isAvailableExternally() const {
return swift::isAvailableExternally(getLinkage());
}
/// Helper method which returns true if the linkage of the SILFunction
/// indicates that the object's definition might be required outside the
/// current SILModule.
bool isPossiblyUsedExternally() const;
/// Helper method which returns whether this function should be preserved so
/// it can potentially be used in the debugger.
bool shouldBePreservedForDebugger() const;
/// In addition to isPossiblyUsedExternally() it returns also true if this
/// is a (private or internal) vtable method which can be referenced by
/// vtables of derived classes outside the compilation unit.
bool isExternallyUsedSymbol() const;
/// Return whether this function may be referenced by C code.
bool hasCReferences() const { return HasCReferences; }
void setHasCReferences(bool value) { HasCReferences = value; }
/// Returns the availability context used to determine if the function's
/// symbol should be weakly referenced across module boundaries.
AvailabilityContext getAvailabilityForLinkage() const {
return Availability;
}
void setAvailabilityForLinkage(AvailabilityContext availability) {
Availability = availability;
}
/// Returns whether this function's symbol must always be weakly referenced
/// across module boundaries.
bool isAlwaysWeakImported() const { return IsAlwaysWeakImported; }
void setIsAlwaysWeakImported(bool value) { IsAlwaysWeakImported = value; }
bool isWeakImported(ModuleDecl *module) const;
/// Returns whether this function implementation can be dynamically replaced.
IsDynamicallyReplaceable_t isDynamicallyReplaceable() const {
return IsDynamicallyReplaceable_t(IsDynamicReplaceable);
}
void setIsDynamic(IsDynamicallyReplaceable_t value = IsDynamic) {
IsDynamicReplaceable = value;
assert(!Transparent || !IsDynamicReplaceable);
}
IsExactSelfClass_t isExactSelfClass() const {
return IsExactSelfClass_t(ExactSelfClass);
}
void setIsExactSelfClass(IsExactSelfClass_t t) {
ExactSelfClass = t;
}
IsDistributed_t isDistributed() const {
return IsDistributed_t(IsDistributed);
}
void
setIsDistributed(IsDistributed_t value = IsDistributed_t::IsDistributed) {
IsDistributed = value;
}
IsRuntimeAccessible_t isRuntimeAccessible() const {
return IsRuntimeAccessible_t(IsRuntimeAccessible);
}
void setIsRuntimeAccessible(IsRuntimeAccessible_t value =
IsRuntimeAccessible_t::IsRuntimeAccessible) {
IsRuntimeAccessible = value;
}
bool needsStackProtection() const { return stackProtection; }
void setNeedStackProtection(bool needSP) { stackProtection = needSP; }
/// Get the DeclContext of this function.
DeclContext *getDeclContext() const { return DeclCtxt; }
/// \returns True if the function is marked with the @_semantics attribute
/// and has special semantics that the optimizer can use to optimize the
/// function.
bool hasSemanticsAttrs() const { return !SemanticsAttrSet.empty(); }
/// \returns True if the function has a semantic attribute that starts with a
/// specific string.
///
/// TODO: This needs a better name.
bool hasSemanticsAttrThatStartsWith(StringRef S) {
return count_if(getSemanticsAttrs(), [&S](const std::string &Attr) -> bool {
return StringRef(Attr).starts_with(S);
});
}
/// \returns the semantics tag that describes this function.
ArrayRef<std::string> getSemanticsAttrs() const { return SemanticsAttrSet; }
/// \returns True if the function has the semantics flag \p Value;
bool hasSemanticsAttr(StringRef Value) const {
return count(SemanticsAttrSet, Value);
}
/// Add the given semantics attribute to the attr list set.
void addSemanticsAttr(StringRef Ref) {
if (hasSemanticsAttr(Ref))
return;
SemanticsAttrSet.push_back(Ref.str());
std::sort(SemanticsAttrSet.begin(), SemanticsAttrSet.end());
}