-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathParseSIL.cpp
8927 lines (7918 loc) · 315 KB
/
ParseSIL.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
//===--- ParseSIL.cpp - SIL File Parsing logic ----------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "SILParser.h"
#include "SILParserFunctionBuilder.h"
#include "SILParserState.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SILGenRequests.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/ParseSILSupport.h"
#include "swift/SIL/AbstractionPattern.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/ParseTestSpecification.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILDebugScope.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILMoveOnlyDeinit.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/Sema/SILTypeResolutionContext.h"
#include "swift/Subsystems.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/SaveAndRestore.h"
#include <variant>
using namespace swift;
static llvm::cl::opt<bool>
ParseSerializedSIL("parse-serialized-sil",
llvm::cl::desc("Parse the output of a serialized module"));
static llvm::cl::opt<bool>
DisableInputVerify("sil-disable-input-verify",
llvm::cl::desc("Disable verification of input SIL"),
llvm::cl::init(false));
// Option for testing -silgen-cleanup -enable-complete-ossa
static llvm::cl::opt<bool>
ParseIncompleteOSSA("parse-incomplete-ossa",
llvm::cl::desc("Parse OSSA with incomplete lifetimes"));
//===----------------------------------------------------------------------===//
// SILParserState implementation
//===----------------------------------------------------------------------===//
SILParserState::~SILParserState() {
if (!ForwardRefFns.empty()) {
for (auto Entry : ForwardRefFns) {
if (Entry.second.Loc.isValid()) {
M.getASTContext().Diags.diagnose(Entry.second.Loc,
diag::sil_use_of_undefined_value,
Entry.first.str());
}
}
}
// Turn any debug-info-only function declarations into zombies.
markZombies();
}
void SILParserState::markZombies() {
for (auto *Fn : PotentialZombieFns) {
if (Fn->isExternalDeclaration() && !Fn->isZombie()) {
Fn->setInlined();
M.eraseFunction(Fn);
}
}
}
std::unique_ptr<SILModule>
ParseSILModuleRequest::evaluate(Evaluator &evaluator,
ASTLoweringDescriptor desc) const {
auto *SF = desc.getSourceFileToParse();
assert(SF);
auto bufferID = SF->getBufferID();
auto silMod = SILModule::createEmptyModule(desc.context, desc.conv,
desc.opts);
SILParserState parserState(*silMod.get());
Parser parser(bufferID, *SF, &parserState);
PrettyStackTraceParser StackTrace(parser);
if (ParseSerializedSIL) {
silMod.get()->setParsedAsSerializedSIL();
}
auto hadError = parser.parseTopLevelSIL();
if (hadError) {
// The rest of the SIL pipeline expects well-formed SIL, so if we encounter
// a parsing error, just return an empty SIL module.
//
// Because the SIL parser's notion of failing with an error is distinct from
// the ASTContext's notion of having emitted a diagnostic, it's possible for
// the parser to fail silently without emitting a diagnostic. This assertion
// ensures that +asserts builds will fail fast. If you crash here, please go
// back and add a diagnostic after identifying where the SIL parser failed.
assert(SF->getASTContext().hadError() &&
"Failed to parse SIL but did not emit any errors!");
return SILModule::createEmptyModule(desc.context, desc.conv, desc.opts);
}
// Mark functions as zombies before calling SILVerifier as functions referred
//to by debug scopes only can fail verifier checks
parserState.markZombies();
// If SIL parsing succeeded, verify the generated SIL.
if (!parser.Diags.hadAnyError() && !DisableInputVerify) {
silMod->verify(/*SingleFunction=*/true, !ParseIncompleteOSSA);
}
return silMod;
}
//===----------------------------------------------------------------------===//
// SILParser
//===----------------------------------------------------------------------===//
bool SILParser::parseSILIdentifier(Identifier &Result, SourceLoc &Loc,
DiagRef D) {
switch (P.Tok.getKind()) {
case tok::identifier:
case tok::dollarident:
Result = P.Context.getIdentifier(P.Tok.getText());
break;
case tok::string_literal: {
// Drop the double quotes.
StringRef rawString = P.Tok.getText().drop_front().drop_back();
Result = P.Context.getIdentifier(rawString);
break;
}
case tok::oper_binary_unspaced: // fixme?
case tok::oper_binary_spaced:
case tok::kw_init:
// A binary operator or `init` can be part of a SILDeclRef.
Result = P.Context.getIdentifier(P.Tok.getText());
break;
default:
// If it's some other keyword, grab an identifier for it.
if (P.Tok.isKeyword()) {
Result = P.Context.getIdentifier(P.Tok.getText());
break;
}
P.diagnose(P.Tok, D);
return true;
}
Loc = P.Tok.getLoc();
P.consumeToken();
return false;
}
bool SILParser::parseVerbatim(StringRef name) {
Identifier tok;
SourceLoc loc;
if (parseSILIdentifier(tok, loc, diag::expected_tok_in_sil_instr, name)) {
return true;
}
if (tok.str() != name) {
P.diagnose(loc, diag::expected_tok_in_sil_instr, name);
return true;
}
return false;
}
SILParser::~SILParser() {
for (auto &Entry : ForwardRefLocalValues) {
if (ValueBase *dummyVal = LocalValues[Entry.first()]) {
dummyVal->replaceAllUsesWith(
SILUndef::get(dummyVal->getFunction(), dummyVal->getType()));
::delete cast<PlaceholderValue>(dummyVal);
}
}
}
/// diagnoseProblems - After a function is fully parse, emit any diagnostics
/// for errors and return true if there were any.
bool SILParser::diagnoseProblems() {
// Check for any uses of basic blocks that were not defined.
if (!UndefinedBlocks.empty()) {
// FIXME: These are going to come out in nondeterministic order.
for (auto Entry : UndefinedBlocks)
P.diagnose(Entry.second.Loc, diag::sil_undefined_basicblock_use,
Entry.second.Item);
HadError = true;
}
if (!ForwardRefLocalValues.empty()) {
// FIXME: These are going to come out in nondeterministic order.
for (auto &Entry : ForwardRefLocalValues)
P.diagnose(Entry.second, diag::sil_use_of_undefined_value,
Entry.first());
HadError = true;
}
return HadError;
}
/// getGlobalNameForDefinition - Given a definition of a global name, look
/// it up and return an appropriate SIL function.
SILFunction *SILParser::getGlobalNameForDefinition(Identifier name,
CanSILFunctionType ty,
SourceLoc sourceLoc) {
SILParserFunctionBuilder builder(SILMod);
auto silLoc = RegularLocation(sourceLoc);
// Check to see if a function of this name has been forward referenced. If so
// complete the forward reference.
auto iter = TUState.ForwardRefFns.find(name);
if (iter != TUState.ForwardRefFns.end()) {
SILFunction *fn = iter->second.Item;
// Verify that the types match up.
if (fn->getLoweredFunctionType() != ty) {
P.diagnose(sourceLoc, diag::sil_value_use_type_mismatch, name.str(),
fn->getLoweredFunctionType(), ty);
P.diagnose(iter->second.Loc, diag::sil_prior_reference);
fn = builder.createFunctionForForwardReference("" /*name*/, ty, silLoc);
}
assert(fn->isExternalDeclaration() && "Forward defns cannot have bodies!");
TUState.ForwardRefFns.erase(iter);
// Move the function to this position in the module.
//
// FIXME: Should we move this functionality into SILParserFunctionBuilder?
SILMod.getFunctionList().remove(fn);
SILMod.getFunctionList().push_back(fn);
return fn;
}
// If we don't have a forward reference, make sure the function hasn't been
// defined already.
if (SILMod.lookUpFunction(name.str()) != nullptr) {
P.diagnose(sourceLoc, diag::sil_value_redefinition, name.str());
return builder.createFunctionForForwardReference("" /*name*/, ty, silLoc);
}
// Otherwise, this definition is the first use of this name.
return builder.createFunctionForForwardReference(name.str(), ty, silLoc);
}
/// getGlobalNameForReference - Given a reference to a global name, look it
/// up and return an appropriate SIL function.
SILFunction *SILParser::getGlobalNameForReference(Identifier name,
CanSILFunctionType funcTy,
SourceLoc sourceLoc,
bool ignoreFwdRef) {
SILParserFunctionBuilder builder(SILMod);
auto silLoc = RegularLocation(sourceLoc);
// Check to see if we have a function by this name already.
if (SILFunction *fn = SILMod.lookUpFunction(name.str())) {
// If so, check for matching types.
if (fn->getLoweredFunctionType() == funcTy) {
return fn;
}
P.diagnose(sourceLoc, diag::sil_value_use_type_mismatch, name.str(),
fn->getLoweredFunctionType(), funcTy);
return builder.createFunctionForForwardReference("" /*name*/, funcTy,
silLoc);
}
// If we didn't find a function, create a new one - it must be a forward
// reference.
auto *fn =
builder.createFunctionForForwardReference(name.str(), funcTy, silLoc);
TUState.ForwardRefFns[name] = {fn, ignoreFwdRef ? SourceLoc() : sourceLoc};
return fn;
}
/// getBBForDefinition - Return the SILBasicBlock for a definition of the
/// specified block.
SILBasicBlock *SILParser::getBBForDefinition(Identifier Name, SourceLoc Loc) {
// If there was no name specified for this block, just create a new one.
if (Name.empty())
return F->createBasicBlock();
SILBasicBlock *&BB = BlocksByName[Name];
// If the block has never been named yet, just create it.
if (BB == nullptr)
return BB = F->createBasicBlock();
// If it already exists, it was either a forward reference or a redefinition.
// If it is a forward reference, it should be in our undefined set.
if (!UndefinedBlocks.erase(BB)) {
// If we have a redefinition, return a new BB to avoid inserting
// instructions after the terminator.
P.diagnose(Loc, diag::sil_basicblock_redefinition, Name);
HadError = true;
return F->createBasicBlock();
}
// FIXME: Splice the block to the end of the function so they come out in the
// right order.
return BB;
}
/// getBBForReference - return the SILBasicBlock of the specified name. The
/// source location is used to diagnose a failure if the block ends up never
/// being defined.
SILBasicBlock *SILParser::getBBForReference(Identifier Name, SourceLoc Loc) {
// If the block has already been created, use it.
SILBasicBlock *&BB = BlocksByName[Name];
if (BB != nullptr)
return BB;
// Otherwise, create it and remember that this is a forward reference so
// that we can diagnose use without definition problems.
BB = F->createBasicBlock();
UndefinedBlocks[BB] = {Name, Loc};
return BB;
}
/// sil-global-name:
/// '@' identifier
bool SILParser::parseGlobalName(Identifier &Name) {
return P.parseToken(tok::at_sign, diag::expected_sil_value_name) ||
parseSILIdentifier(Name, diag::expected_sil_value_name);
}
/// getLocalValue - Get a reference to a local value with the specified name
/// and type.
SILValue SILParser::getLocalValue(UnresolvedValueName Name, SILType Type,
SILLocation Loc, SILBuilder &B) {
if (Name.isUndef())
return SILUndef::get(B.getFunction(), Type);
// Check to see if this is already defined.
ValueBase *&Entry = LocalValues[Name.Name];
if (Entry) {
// If this value is already defined, check it to make sure types match.
SILType EntryTy = Entry->getType();
if (EntryTy != Type) {
HadError = true;
P.diagnose(Name.NameLoc, diag::sil_value_use_type_mismatch, Name.Name,
EntryTy.getRawASTType(), Type.getRawASTType());
// Make sure to return something of the requested type.
return SILUndef::get(B.getFunction(), Type);
}
return SILValue(Entry);
}
// Otherwise, this is a forward reference. Create a dummy node to represent
// it until we see a real definition.
ForwardRefLocalValues[Name.Name] = Name.NameLoc;
Entry = ::new PlaceholderValue(&B.getFunction(), Type);
return Entry;
}
/// setLocalValue - When an instruction or block argument is defined, this
/// method is used to register it and update our symbol table.
void SILParser::setLocalValue(ValueBase *Value, StringRef Name,
SourceLoc NameLoc) {
ValueBase *&Entry = LocalValues[Name];
// If this value was already defined, it is either a redefinition, or a
// specification for a forward referenced value.
if (Entry) {
if (!ForwardRefLocalValues.erase(Name)) {
P.diagnose(NameLoc, diag::sil_value_redefinition, Name);
HadError = true;
return;
}
// If the forward reference was of the wrong type, diagnose this now.
if (Entry->getType() != Value->getType()) {
P.diagnose(NameLoc, diag::sil_value_def_type_mismatch, Name,
Entry->getType().getRawASTType(),
Value->getType().getRawASTType());
HadError = true;
} else {
if (TestSpecsWithRefs.find(Name) != TestSpecsWithRefs.end()) {
for (auto *tsi : TestSpecsWithRefs[Name]) {
tsi->setValueForName(Name, Value);
}
}
// Forward references only live here if they have a single result.
Entry->replaceAllUsesWith(Value);
::delete cast<PlaceholderValue>(Entry);
}
Entry = Value;
return;
}
if (TestSpecsWithRefs.find(Name) != TestSpecsWithRefs.end()) {
for (auto *tsi : TestSpecsWithRefs[Name]) {
tsi->setValueForName(Name, Value);
}
}
// Otherwise, just store it in our map.
Entry = Value;
}
//===----------------------------------------------------------------------===//
// SIL Parsing Logic
//===----------------------------------------------------------------------===//
/// parseSILLinkage - Parse a linkage specifier if present.
/// sil-linkage:
/// /*empty*/ // default depends on whether this is a definition
/// 'public'
/// 'hidden'
/// 'shared'
/// 'private'
/// 'public_external'
/// 'hidden_external'
/// 'private_external'
static bool parseSILLinkage(std::optional<SILLinkage> &Result, Parser &P) {
// Begin by initializing result to our base value of None.
Result = std::nullopt;
// Unfortunate collision with access control keywords.
if (P.Tok.is(tok::kw_public)) {
Result = SILLinkage::Public;
P.consumeToken();
return false;
}
// Unfortunate collision with access control keywords.
if (P.Tok.is(tok::kw_private)) {
Result = SILLinkage::Private;
P.consumeToken();
return false;
}
// If we do not have an identifier, bail. All SILLinkages that we are parsing
// are identifiers.
if (P.Tok.isNot(tok::identifier))
return false;
// Then use a string switch to try and parse the identifier.
Result = llvm::StringSwitch<std::optional<SILLinkage>>(P.Tok.getText())
.Case("non_abi", SILLinkage::PublicNonABI)
.Case("package_non_abi", SILLinkage::PackageNonABI)
.Case("package", SILLinkage::Package)
.Case("hidden", SILLinkage::Hidden)
.Case("shared", SILLinkage::Shared)
.Case("public_external", SILLinkage::PublicExternal)
.Case("package_external", SILLinkage::PackageExternal)
.Case("hidden_external", SILLinkage::HiddenExternal)
.Default(std::nullopt);
// If we succeed, consume the token.
if (Result) {
P.consumeToken(tok::identifier);
}
return false;
}
/// Given whether it's known to be a definition, resolve an optional
/// SIL linkage to a real one.
static SILLinkage resolveSILLinkage(std::optional<SILLinkage> linkage,
bool isDefinition) {
if (linkage.has_value()) {
return linkage.value();
} else if (isDefinition) {
return SILLinkage::DefaultForDefinition;
} else {
return SILLinkage::DefaultForDeclaration;
}
}
namespace {
using SILOptionalAttrValue = std::optional<std::variant<uint64_t, StringRef>>;
} // namespace
/// Returns false if no optional exists. Returns true on both success and
/// failure. On success, the Result string is nonempty. If the optional is
/// assigned to an integer value using an equal, \p value contains the parsed
/// value. Otherwise, value is set to the maximum uint64_t.
///
/// Example: [alignment=$NUM]
static bool parseSILOptional(StringRef &parsedName, SourceLoc &parsedNameLoc,
SILOptionalAttrValue &parsedValue,
SourceLoc &parsedValueLoc, SILParser &parser) {
if (!parser.P.consumeIf(tok::l_square))
return false;
Identifier parsedNameId;
if (parser.parseSILIdentifier(parsedNameId, parsedNameLoc,
diag::expected_in_attribute_list))
return true;
parsedName = parsedNameId.str();
uint64_t parsedIntValue = ~uint64_t(0);
Identifier parsedStringId;
if (parser.P.consumeIf(tok::equal)) {
auto currentTok = parser.P.Tok;
parsedValueLoc = currentTok.getLoc();
if (currentTok.is(tok::integer_literal)) {
if (parser.parseInteger(parsedIntValue,
diag::expected_in_attribute_list)) {
return true;
}
parsedValue = parsedIntValue;
} else {
if (parser.parseSILIdentifier(parsedStringId, parsedValueLoc,
diag::expected_in_attribute_list)) {
return true;
}
parsedValue = parsedStringId.str();
}
}
if (parser.P.parseToken(tok::r_square, diag::expected_in_attribute_list))
return true;
return true;
}
static bool parseSILOptional(StringRef &attrName, SourceLoc &attrLoc,
SILParser &SP) {
SILOptionalAttrValue parsedValue;
SourceLoc parsedValueLoc;
return parseSILOptional(attrName, attrLoc, parsedValue, parsedValueLoc, SP);
}
static bool parseSILOptional(StringRef &attrName, SILParser &SP) {
SourceLoc attrLoc;
return parseSILOptional(attrName, attrLoc, SP);
}
/// Parse an option attribute ('[' Expected ']')?
static bool parseSILOptional(bool &Result, SILParser &SP, StringRef Expected) {
StringRef Optional;
SourceLoc Loc;
if (parseSILOptional(Optional, Loc, SP)) {
if (Optional != Expected) {
SP.P.diagnose(Loc, diag::sil_invalid_attribute_for_expected, Optional,
Expected);
return true;
}
Result = true;
}
return false;
}
// If the qualifier string is unrecognized, then diagnose and fail.
//
// If the qualifier is absent, then succeed and set the result to None.
// The caller can decide how to proceed with an absent qualifier.
//
// Usage:
// auto parseQualifierName = [](StringRef Str) {
// return llvm::StringSwitch<std::optional<SomeQualifier>>(Str)
// .Case("one", SomeQualifier::One)
// .Case("two", SomeQualifier::Two)
// .Default(None);
// };
// if (parseSILQualifier<SomeQualifier>(Qualifier, parseQualifierName))
// return true;
template <typename T>
bool SILParser::parseSILQualifier(
std::optional<T> &result,
llvm::function_ref<std::optional<T>(StringRef)> parseName) {
auto loc = P.Tok.getLoc();
StringRef Str;
// If we do not parse '[' ... ']',
if (!parseSILOptional(Str, *this)) {
result = std::nullopt;
return false;
}
result = parseName(Str);
if (!result) {
P.diagnose(loc, diag::unrecognized_sil_qualifier);
return true;
}
return false;
}
/// Remap RequirementReps to Requirements.
void SILParser::convertRequirements(ArrayRef<RequirementRepr> From,
SmallVectorImpl<Requirement> &To,
SmallVectorImpl<Type> &typeErasedParams) {
if (From.empty()) {
To.clear();
return;
}
// Use parser lexical scopes to resolve references
// to the generic parameters.
auto ResolveToInterfaceType = [&](TypeRepr *TyR) -> Type {
return performTypeResolution(TyR, /*IsSILType=*/false, ContextGenericSig,
ContextGenericParams);
};
for (auto &Req : From) {
if (Req.getKind() == RequirementReprKind::SameType) {
auto FirstType = ResolveToInterfaceType(Req.getFirstTypeRepr());
auto SecondType = ResolveToInterfaceType(Req.getSecondTypeRepr());
Requirement ConvertedRequirement(RequirementKind::SameType, FirstType,
SecondType);
To.push_back(ConvertedRequirement);
continue;
}
if (Req.getKind() == RequirementReprKind::TypeConstraint) {
auto Subject = ResolveToInterfaceType(Req.getSubjectRepr());
auto Constraint = ResolveToInterfaceType(Req.getConstraintRepr());
Requirement ConvertedRequirement(RequirementKind::Conformance, Subject,
Constraint);
To.push_back(ConvertedRequirement);
continue;
}
if (Req.getKind() == RequirementReprKind::LayoutConstraint) {
auto Subject = ResolveToInterfaceType(Req.getSubjectRepr());
Requirement ConvertedRequirement(RequirementKind::Layout, Subject,
Req.getLayoutConstraint());
To.push_back(ConvertedRequirement);
if (SILMod.getASTContext().LangOpts.hasFeature(Feature::LayoutPrespecialization)) {
if (auto *attributedTy = dyn_cast<AttributedTypeRepr>(Req.getSubjectRepr())) {
if (attributedTy->has(TypeAttrKind::NoMetadata)) {
typeErasedParams.push_back(Subject);
}
}
}
continue;
}
llvm_unreachable("Unsupported requirement kind");
}
}
static bool parseDeclSILOptional(
bool *isTransparent, SerializedKind_t *serializedKind, bool *isCanonical,
bool *hasOwnershipSSA, IsThunk_t *isThunk,
IsDynamicallyReplaceable_t *isDynamic, IsDistributed_t *isDistributed,
IsRuntimeAccessible_t *isRuntimeAccessible,
ForceEnableLexicalLifetimes_t *forceEnableLexicalLifetimes,
UseStackForPackMetadata_t *useStackForPackMetadata,
bool *hasUnsafeNonEscapableResult, IsExactSelfClass_t *isExactSelfClass,
SILFunction **dynamicallyReplacedFunction,
SILFunction **usedAdHocRequirementWitness, Identifier *objCReplacementFor,
SILFunction::Purpose *specialPurpose, Inline_t *inlineStrategy,
OptimizationMode *optimizationMode, PerformanceConstraints *perfConstraints,
bool *isPerformanceConstraint, bool *markedAsUsed, StringRef *section,
bool *isLet, bool *isWeakImported, bool *needStackProtection, bool *isSpecialized,
AvailabilityRange *availability, bool *isWithoutActuallyEscapingThunk,
SmallVectorImpl<std::string> *Semantics,
SmallVectorImpl<ParsedSpecAttr> *SpecAttrs, ValueDecl **ClangDecl,
EffectsKind *MRK, SILParser &SP, SILModule &M) {
while (SP.P.consumeIf(tok::l_square)) {
if (isLet && SP.P.Tok.is(tok::kw_let)) {
*isLet = true;
SP.P.consumeToken(tok::kw_let);
SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
continue;
}
else if (SP.P.Tok.isNot(tok::identifier)) {
SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
return true;
} else if (isTransparent && SP.P.Tok.getText() == "transparent")
*isTransparent = true;
else if (serializedKind && SP.P.Tok.getText() == "serialized")
*serializedKind = IsSerialized;
else if (serializedKind && SP.P.Tok.getText() == "serialized_for_package")
*serializedKind = IsSerializedForPackage;
else if (isDynamic && SP.P.Tok.getText() == "dynamically_replacable")
*isDynamic = IsDynamic;
else if (isDistributed && SP.P.Tok.getText() == "distributed")
*isDistributed = IsDistributed;
else if (isRuntimeAccessible && SP.P.Tok.getText() == "runtime_accessible")
*isRuntimeAccessible = IsRuntimeAccessible;
else if (forceEnableLexicalLifetimes &&
SP.P.Tok.getText() == "lexical_lifetimes")
*forceEnableLexicalLifetimes = DoForceEnableLexicalLifetimes;
else if (useStackForPackMetadata &&
SP.P.Tok.getText() == "no_onstack_pack_metadata")
*useStackForPackMetadata = DoNotUseStackForPackMetadata;
else if (hasUnsafeNonEscapableResult &&
SP.P.Tok.getText() == "unsafe_nonescapable_result")
*hasUnsafeNonEscapableResult = hasUnsafeNonEscapableResult;
else if (isExactSelfClass && SP.P.Tok.getText() == "exact_self_class")
*isExactSelfClass = IsExactSelfClass;
else if (isCanonical && SP.P.Tok.getText() == "canonical")
*isCanonical = true;
else if (hasOwnershipSSA && SP.P.Tok.getText() == "ossa")
*hasOwnershipSSA = true;
else if (needStackProtection && SP.P.Tok.getText() == "stack_protection")
*needStackProtection = true;
else if (isSpecialized && SP.P.Tok.getText() == "specialized")
*isSpecialized = true;
else if (isThunk && SP.P.Tok.getText() == "thunk")
*isThunk = IsThunk;
else if (isThunk && SP.P.Tok.getText() == "signature_optimized_thunk")
*isThunk = IsSignatureOptimizedThunk;
else if (isThunk && SP.P.Tok.getText() == "reabstraction_thunk")
*isThunk = IsReabstractionThunk;
else if (isThunk && SP.P.Tok.getText() == "back_deployed_thunk")
*isThunk = IsBackDeployedThunk;
else if (isWithoutActuallyEscapingThunk
&& SP.P.Tok.getText() == "without_actually_escaping")
*isWithoutActuallyEscapingThunk = true;
else if (specialPurpose && SP.P.Tok.getText() == "global_init")
*specialPurpose = SILFunction::Purpose::GlobalInit;
else if (specialPurpose && SP.P.Tok.getText() == "lazy_getter")
*specialPurpose = SILFunction::Purpose::LazyPropertyGetter;
else if (specialPurpose && SP.P.Tok.getText() == "global_init_once_fn")
*specialPurpose = SILFunction::Purpose::GlobalInitOnceFunction;
else if (isWeakImported && SP.P.Tok.getText() == "weak_imported") {
if (M.getASTContext().LangOpts.Target.isOSBinFormatCOFF())
SP.P.diagnose(SP.P.Tok, diag::attr_name_unsupported_on_target,
SP.P.Tok.getText(),
M.getASTContext().LangOpts.Target.str());
else
*isWeakImported = true;
} else if (availability && SP.P.Tok.getText() == "available") {
SP.P.consumeToken(tok::identifier);
SourceRange range;
llvm::VersionTuple version;
if (SP.P.parseVersionTuple(version, range,
diag::sil_availability_expected_version))
return true;
*availability = AvailabilityRange(version);
SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
continue;
} else if (inlineStrategy && SP.P.Tok.getText() == "noinline")
*inlineStrategy = NoInline;
else if (optimizationMode && SP.P.Tok.getText() == "Onone")
*optimizationMode = OptimizationMode::NoOptimization;
else if (optimizationMode && SP.P.Tok.getText() == "Ospeed")
*optimizationMode = OptimizationMode::ForSpeed;
else if (optimizationMode && SP.P.Tok.getText() == "Osize")
*optimizationMode = OptimizationMode::ForSize;
else if (perfConstraints && SP.P.Tok.getText() == "no_locks")
*perfConstraints = PerformanceConstraints::NoLocks;
else if (perfConstraints && SP.P.Tok.getText() == "no_allocation")
*perfConstraints = PerformanceConstraints::NoAllocation;
else if (perfConstraints && SP.P.Tok.getText() == "no_runtime")
*perfConstraints = PerformanceConstraints::NoRuntime;
else if (perfConstraints && SP.P.Tok.getText() == "no_existentials")
*perfConstraints = PerformanceConstraints::NoExistentials;
else if (perfConstraints && SP.P.Tok.getText() == "no_objc_bridging")
*perfConstraints = PerformanceConstraints::NoObjCBridging;
else if (isPerformanceConstraint && SP.P.Tok.getText() == "perf_constraint")
*isPerformanceConstraint = true;
else if (markedAsUsed && SP.P.Tok.getText() == "used")
*markedAsUsed = true;
else if (section && SP.P.Tok.getText() == "section") {
SP.P.consumeToken(tok::identifier);
if (SP.P.Tok.getKind() != tok::string_literal) {
SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
return true;
}
// Drop the double quotes.
StringRef rawString = SP.P.Tok.getText().drop_front().drop_back();
*section = SP.P.Context.getIdentifier(rawString).str();
SP.P.consumeToken(tok::string_literal);
SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
continue;
}
else if (inlineStrategy && SP.P.Tok.getText() == "always_inline")
*inlineStrategy = AlwaysInline;
else if (MRK && SP.P.Tok.getText() == "readnone")
*MRK = EffectsKind::ReadNone;
else if (MRK && SP.P.Tok.getText() == "readonly")
*MRK = EffectsKind::ReadOnly;
else if (MRK && SP.P.Tok.getText() == "readwrite")
*MRK = EffectsKind::ReadWrite;
else if (MRK && SP.P.Tok.getText() == "releasenone")
*MRK = EffectsKind::ReleaseNone;
else if (dynamicallyReplacedFunction && SP.P.Tok.getText() == "dynamic_replacement_for") {
SP.P.consumeToken(tok::identifier);
if (SP.P.Tok.getKind() != tok::string_literal) {
SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
return true;
}
// Drop the double quotes.
StringRef replacedFunc = SP.P.Tok.getText().drop_front().drop_back();
SILFunction *Func = M.lookUpFunction(replacedFunc.str());
if (!Func) {
Identifier Id = SP.P.Context.getIdentifier(replacedFunc);
SP.P.diagnose(SP.P.Tok, diag::sil_dynamically_replaced_func_not_found,
Id);
return true;
}
*dynamicallyReplacedFunction = Func;
SP.P.consumeToken(tok::string_literal);
SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
continue;
} else if (usedAdHocRequirementWitness && SP.P.Tok.getText() == "ref_adhoc_requirement_witness") {
SP.P.consumeToken(tok::identifier);
if (SP.P.Tok.getKind() != tok::string_literal) {
SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
return true;
}
// Drop the double quotes.
StringRef witnessFunc = SP.P.Tok.getText().drop_front().drop_back();
SILFunction *Func = M.lookUpFunction(witnessFunc.str());
if (!Func) {
Identifier Id = SP.P.Context.getIdentifier(witnessFunc);
SP.P.diagnose(SP.P.Tok, diag::sil_adhoc_requirement_witness_func_not_found,
Id);
return true;
}
*usedAdHocRequirementWitness = Func;
SP.P.consumeToken(tok::string_literal);
SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
continue;
} else if (objCReplacementFor &&
SP.P.Tok.getText() == "objc_replacement_for") {
SP.P.consumeToken(tok::identifier);
if (SP.P.Tok.getKind() != tok::string_literal) {
SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
return true;
}
// Drop the double quotes.
StringRef replacedFunc = SP.P.Tok.getText().drop_front().drop_back();
*objCReplacementFor = SP.P.Context.getIdentifier(replacedFunc);
SP.P.consumeToken(tok::string_literal);
SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
continue;
} else if (Semantics && SP.P.Tok.getText() == "_semantics") {
SP.P.consumeToken(tok::identifier);
if (SP.P.Tok.getKind() != tok::string_literal) {
SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
return true;
}
// Drop the double quotes.
StringRef rawString = SP.P.Tok.getText().drop_front().drop_back();
Semantics->push_back(rawString.str());
SP.P.consumeToken(tok::string_literal);
SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
continue;
} else if (SpecAttrs && SP.P.Tok.getText() == "_specialize") {
SourceLoc AtLoc = SP.P.Tok.getLoc();
SourceLoc Loc(AtLoc);
// Parse a _specialized attribute, building a parsed substitution list
// and pushing a new ParsedSpecAttr on the SpecAttrs list. Conformances
// cannot be generated until the function declaration is fully parsed so
// that the function's generic signature can be consulted.
ParsedSpecAttr SpecAttr;
SpecAttr.requirements = {};
SpecAttr.exported = false;
SpecAttr.kind = SILSpecializeAttr::SpecializationKind::Full;
SpecializeAttr *Attr;
StringRef targetFunctionName;
ModuleDecl *module = nullptr;
AvailabilityRange availability = AvailabilityRange::alwaysAvailable();
if (!SP.P.parseSpecializeAttribute(
tok::r_square, AtLoc, Loc, Attr, &availability,
[&targetFunctionName](Parser &P) -> bool {
if (P.Tok.getKind() != tok::string_literal) {
P.diagnose(P.Tok, diag::expected_in_attribute_list);
return true;
}
// Drop the double quotes.
targetFunctionName = P.Tok.getText().drop_front().drop_back();
P.consumeToken(tok::string_literal);
return true;
},
[&module](Parser &P) -> bool {
if (P.Tok.getKind() != tok::identifier) {
P.diagnose(P.Tok, diag::expected_in_attribute_list);
return true;
}
auto ident = P.Context.getIdentifier(P.Tok.getText());
module = P.Context.getModuleByIdentifier(ident);
assert(module);
P.consumeToken();
return true;
}))
return true;
SILFunction *targetFunction = nullptr;
if (!targetFunctionName.empty()) {
targetFunction = M.lookUpFunction(targetFunctionName.str());
if (!targetFunction) {
Identifier Id = SP.P.Context.getIdentifier(targetFunctionName);
SP.P.diagnose(SP.P.Tok, diag::sil_specialize_target_func_not_found,
Id);
return true;
}
}
// Convert SpecializeAttr into ParsedSpecAttr.
SpecAttr.requirements = Attr->getTrailingWhereClause()->getRequirements();
SpecAttr.kind = Attr->getSpecializationKind() ==
swift::SpecializeAttr::SpecializationKind::Full
? SILSpecializeAttr::SpecializationKind::Full
: SILSpecializeAttr::SpecializationKind::Partial;
SpecAttr.exported = Attr->isExported();
SpecAttr.target = targetFunction;
SpecAttr.availability = availability;
SpecAttrs->emplace_back(SpecAttr);
if (!Attr->getSPIGroups().empty()) {
SpecAttr.spiGroupID = Attr->getSPIGroups()[0];
}
continue;
}
else if (ClangDecl && SP.P.Tok.getText() == "clang") {
SP.P.consumeToken(tok::identifier);
if (SP.parseSILDottedPathWithoutPound(*ClangDecl))
return true;
SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
continue;
} else {
SP.P.diagnose(SP.P.Tok, diag::expected_in_attribute_list);
return true;
}
SP.P.consumeToken(tok::identifier);
SP.P.parseToken(tok::r_square, diag::expected_in_attribute_list);
}
return false;
}
Type SILParser::performTypeResolution(TypeRepr *TyR, bool IsSILType,
GenericSignature GenericSig,
GenericParamList *GenericParams) {
if (!GenericSig)
GenericSig = ContextGenericSig;
SILTypeResolutionContext SILContext(IsSILType, GenericParams,
&OpenedPackElements);
return swift::performTypeResolution(TyR, P.Context, GenericSig,
&SILContext, &P.SF);
}
/// Find the top-level ValueDecl or Module given a name.
static llvm::PointerUnion<ValueDecl *, ModuleDecl *>
lookupTopDecl(Parser &P, DeclBaseName Name, bool typeLookup) {
// Use UnqualifiedLookup to look through all of the imports.
UnqualifiedLookupOptions options;
if (typeLookup)
options |= UnqualifiedLookupFlags::TypeLookup;
auto &ctx = P.SF.getASTContext();
auto descriptor = UnqualifiedLookupDescriptor(DeclNameRef(Name), &P.SF);
auto lookup = evaluateOrDefault(ctx.evaluator,
UnqualifiedLookupRequest{descriptor}, {});
lookup.filter([](LookupResultEntry entry, bool isOuter) -> bool {
return !isa<MacroDecl>(entry.getValueDecl());
});
assert(lookup.size() == 1);
return lookup.back().getValueDecl();
}
/// Find the ValueDecl given an interface type and a member name.
static ValueDecl *lookupMember(Parser &P, Type Ty, DeclBaseName Name,