-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathKeyPathProjector.cpp
703 lines (585 loc) · 28 KB
/
KeyPathProjector.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
//===-- KeyPathProjector.cpp - Project a static key path --------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Utility class to project a statically known key path
/// expression to a direct property access sequence.
///
//===----------------------------------------------------------------------===//
#include "swift/SILOptimizer/Utils/KeyPathProjector.h"
#include "swift/SIL/SILInstruction.h"
using namespace swift;
// Projectors to handle individual key path components.
/// Projects the root of a key path application.
class RootProjector : public KeyPathProjector {
public:
RootProjector(SILValue root, SILLocation loc, SILBuilder &builder)
: KeyPathProjector(loc, builder), root(root) {}
void project(AccessType accessType,
std::function<void (SILValue)> callback) override {
if (accessType == AccessType::Set) {
// We're setting the identity key path (\.self). The callback
// expects an uninitialized address, so destroy the old value.
builder.emitDestroyAddr(loc, root);
}
callback(root);
}
bool isStruct() override {
return root->getType().getStructOrBoundGenericStruct() != nullptr;
}
private:
SILValue root;
};
/// Projects a single key path component.
class ComponentProjector : public KeyPathProjector {
protected:
ComponentProjector(const KeyPathPatternComponent &component,
std::unique_ptr<KeyPathProjector> parent,
SILLocation loc, SILBuilder &builder)
: KeyPathProjector(loc, builder),
component(component), parent(std::move(parent)) {}
/// The key path component.
const KeyPathPatternComponent &component;
/// The projector for the previous components.
std::unique_ptr<KeyPathProjector> parent;
bool isStruct() override {
auto type = component.getComponentType();
return type.getStructOrBoundGenericStruct() != nullptr;
}
~ComponentProjector() override {};
};
/// Ends the begin_access "scope" if a begin_access was inserted for optimizing
/// a keypath pattern.
static void insertEndAccess(BeginAccessInst *&beginAccess,
SILBuilder &builder) {
if (beginAccess) {
builder.createEndAccess(beginAccess->getLoc(), beginAccess,
/*aborted*/ false);
beginAccess = nullptr;
}
}
class StoredPropertyProjector : public ComponentProjector {
public:
StoredPropertyProjector(const KeyPathPatternComponent &component,
std::unique_ptr<KeyPathProjector> parent,
BeginAccessInst *&beginAccess,
SILLocation loc, SILBuilder &builder)
: ComponentProjector(component, std::move(parent), loc, builder),
beginAccess(beginAccess) {}
void project(AccessType accessType,
std::function<void(SILValue addr)> callback) override {
assert(component.getKind() ==
KeyPathPatternComponent::Kind::StoredProperty);
VarDecl *storedProperty = component.getStoredPropertyDecl();
if (parent->isStruct()) {
// Reading a struct field -> reading the struct
// Writing or modifying a struct field -> modifying the struct
AccessType parentAccessType;
if (accessType == AccessType::Get)
parentAccessType = AccessType::Get;
else
parentAccessType = AccessType::Modify;
parent->project(parentAccessType, [&](SILValue parentValue) {
auto addr = builder.createStructElementAddr(loc, parentValue, storedProperty);
// If we're setting, destroy the old value (the callback expects uninitialized memory)
if (accessType == AccessType::Set)
builder.createDestroyAddr(loc, addr);
callback(addr);
});
} else {
// Accessing a class member -> reading the class
parent->project(AccessType::Get, [&](SILValue parentValue) {
SingleValueInstruction *Ref = builder.createLoad(loc, parentValue,
LoadOwnershipQualifier::Unqualified);
// If we were previously accessing a class member, we're done now.
insertEndAccess(beginAccess, builder);
// Handle the case where the storedProperty is in a super class.
while (Ref->getType().getClassOrBoundGenericClass() !=
storedProperty->getDeclContext()) {
SILType superCl = Ref->getType().getSuperclass();
if (!superCl) {
// This should never happen, because the property should be in the
// decl or in a superclass of it. Just handle this to be on the safe
// side.
callback(SILValue());
return;
}
Ref = builder.createUpcast(loc, Ref, superCl);
}
SILValue addr = builder.createRefElementAddr(loc, Ref, storedProperty);
// Class members need access enforcement.
if (builder.getModule().getOptions().EnforceExclusivityDynamic) {
beginAccess = builder.createBeginAccess(loc, addr, SILAccessKind::Read,
SILAccessEnforcement::Dynamic,
/*noNestedConflict*/ false,
/*fromBuiltin*/ false);
if (accessType != AccessType::Get)
beginAccess->setAccessKind(SILAccessKind::Modify);
addr = beginAccess;
}
// If we're setting, destroy the old value (the callback expects uninitialized memory)
if (accessType == AccessType::Set)
builder.createDestroyAddr(loc, addr);
callback(addr);
// if a child hasn't started a new access (i.e. beginAccess is unchanged),
// end the access now
if (beginAccess == addr) {
insertEndAccess(beginAccess, builder);
}
});
}
}
private:
BeginAccessInst *&beginAccess;
};
class TupleElementProjector : public ComponentProjector {
public:
TupleElementProjector(const KeyPathPatternComponent &component,
std::unique_ptr<KeyPathProjector> parent,
SILLocation loc, SILBuilder &builder)
: ComponentProjector(component, std::move(parent), loc, builder) {}
void project(AccessType accessType,
std::function<void(SILValue addr)> callback) override {
assert(component.getKind() ==
KeyPathPatternComponent::Kind::TupleElement);
// Reading a tuple field -> reading the tuple
// Writing or modifying a tuple field -> modifying the tuple
AccessType parentAccessType;
if (accessType == AccessType::Get)
parentAccessType = AccessType::Get;
else
parentAccessType = AccessType::Modify;
parent->project(parentAccessType, [&](SILValue parentValue) {
auto addr = builder.createTupleElementAddr(loc, parentValue, component.getTupleIndex());
// If we're setting, destroy the old value (the callback expects uninitialized memory)
if (accessType == AccessType::Set)
builder.createDestroyAddr(loc, addr);
callback(addr);
});
}
};
class GettablePropertyProjector : public ComponentProjector {
public:
GettablePropertyProjector(KeyPathInst *keyPath,
const KeyPathPatternComponent &component,
std::unique_ptr<KeyPathProjector> parent,
SubstitutionMap subs, BeginAccessInst *&beginAccess,
SILLocation loc, SILBuilder &builder)
: ComponentProjector(component, std::move(parent), loc, builder),
keyPath(keyPath), subs(subs), beginAccess(beginAccess) {}
void project(AccessType accessType,
std::function<void(SILValue addr)> callback) override {
assert(component.getKind() ==
KeyPathPatternComponent::Kind::GettableProperty ||
component.getKind() ==
KeyPathPatternComponent::Kind::SettableProperty);
assert(accessType == AccessType::Get && "property is not settable");
parent->project(accessType, [&](SILValue parentValue) {
auto getter = component.getComputedPropertyGetter();
// The callback expects a memory address it can read from,
// so allocate a buffer.
auto &function = builder.getFunction();
auto substType = component.getComponentType().subst(
keyPath->getSubstitutions(), llvm::None);
SILType type = function.getLoweredType(
Lowering::AbstractionPattern::getOpaque(), substType);
auto addr = builder.createAllocStack(loc, type);
assertHasNoContext();
assert(getter->getConventions().getNumSILArguments());
auto ref = builder.createFunctionRef(loc, getter);
builder.createApply(loc, ref, subs, {addr, parentValue});
// If we were previously accessing a class member, we're done now.
insertEndAccess(beginAccess, builder);
callback(addr);
builder.createDestroyAddr(loc, addr);
builder.createDeallocStack(loc, addr);
});
}
protected:
KeyPathInst *keyPath;
SubstitutionMap subs;
BeginAccessInst *&beginAccess;
void assertHasNoContext() {
assert(component.getSubscriptIndices().empty() &&
component.getExternalSubstitutions().empty() &&
"cannot yet optimize key path component with external context; "
"we should have checked for this before trying to project");
}
};
class SettablePropertyProjector : public GettablePropertyProjector {
public:
SettablePropertyProjector(KeyPathInst *keyPath,
const KeyPathPatternComponent &component,
std::unique_ptr<KeyPathProjector> parent,
SubstitutionMap subs, BeginAccessInst *&beginAccess,
SILLocation loc, SILBuilder &builder)
: GettablePropertyProjector(keyPath, component, std::move(parent),
subs, beginAccess, loc, builder) {}
void project(AccessType accessType,
std::function<void(SILValue addr)> callback) override {
assert(component.getKind() ==
KeyPathPatternComponent::Kind::GettableProperty ||
component.getKind() ==
KeyPathPatternComponent::Kind::SettableProperty);
switch (accessType) {
case AccessType::Get:
GettablePropertyProjector::project(accessType, callback);
break;
case AccessType::Modify:
case AccessType::Set:
AccessType parentAccessType;
if (component.isComputedSettablePropertyMutating()) {
// A mutating setter modifies the parent
parentAccessType = AccessType::Modify;
if (beginAccess) {
beginAccess->setAccessKind(SILAccessKind::Modify);
}
} else {
parentAccessType = AccessType::Get;
}
parent->project(parentAccessType, [&](SILValue parentValue) {
auto getter = component.getComputedPropertyGetter();
auto setter = component.getComputedPropertySetter();
// The callback expects a memory address it can write to,
// so allocate a writeback buffer.
auto &function = builder.getFunction();
auto substType = component.getComponentType().subst(
keyPath->getSubstitutions(), llvm::None);
SILType type = function.getLoweredType(
Lowering::AbstractionPattern::getOpaque(), substType);
auto addr = builder.createAllocStack(loc, type);
assertHasNoContext();
assert(getter->getConventions().getNumSILArguments());
assert(setter->getConventions().getNumSILArguments());
// If this is a modify, we need to call the getter and
// store the result in the writeback buffer.
if (accessType == AccessType::Modify) {
auto getterRef = builder.createFunctionRef(loc, getter);
builder.createApply(loc, getterRef, subs, {addr, parentValue});
}
// The callback function will write into the writeback buffer.
callback(addr);
// Pass the value from the writeback buffer to the setter.
auto setterRef = builder.createFunctionRef(loc, setter);
builder.createApply(loc, setterRef, subs, {addr, parentValue});
// Deallocate the writeback buffer.
builder.createDestroyAddr(loc, addr);
builder.createDeallocStack(loc, addr);
});
break;
}
}
};
class OptionalWrapProjector : public ComponentProjector {
public:
OptionalWrapProjector(KeyPathInst *kpInst,
const KeyPathPatternComponent &component,
std::unique_ptr<KeyPathProjector> parent,
SILLocation loc, SILBuilder &builder)
: ComponentProjector(component, std::move(parent), loc, builder),
keyPath(kpInst) {}
void project(AccessType accessType,
std::function<void(SILValue addr)> callback) override {
assert(component.getKind() ==
KeyPathPatternComponent::Kind::OptionalWrap);
assert(accessType == AccessType::Get && "optional wrap components are immutable");
parent->project(AccessType::Get, [&](SILValue parentValue) {
auto &function = builder.getFunction();
auto substType = component.getComponentType().subst(
keyPath->getSubstitutions(), llvm::None);
SILType optType = function.getLoweredType(
Lowering::AbstractionPattern::getOpaque(), substType);
SILType objType = optType.getOptionalObjectType().getAddressType();
assert(objType && "optional wrap must return an optional");
// Allocate a buffer for the result.
auto optAddr = builder.createAllocStack(loc, optType);
// Store the parent result in the enum payload address.
auto someDecl = builder.getASTContext().getOptionalSomeDecl();
auto objAddr = builder.createInitEnumDataAddr(loc, optAddr,
someDecl, objType);
builder.createCopyAddr(loc, parentValue, objAddr, IsNotTake, IsInitialization);
// Initialize the Optional enum.
builder.createInjectEnumAddr(loc, optAddr, someDecl);
callback(optAddr);
// Destroy the Optional.
builder.createDestroyAddr(loc, optAddr);
builder.createDeallocStack(loc, optAddr);
});
}
private:
KeyPathInst *keyPath;
};
class OptionalForceProjector : public ComponentProjector {
public:
OptionalForceProjector(const KeyPathPatternComponent &component,
std::unique_ptr<KeyPathProjector> parent,
SILLocation loc, SILBuilder &builder)
: ComponentProjector(component, std::move(parent), loc, builder) {}
void project(AccessType accessType,
std::function<void(SILValue addr)> callback) override {
assert(component.getKind() ==
KeyPathPatternComponent::Kind::OptionalForce);
parent->project(accessType, [&](SILValue optAddr) {
auto &ctx = builder.getASTContext();
auto noneDecl = ctx.getOptionalNoneDecl();
auto someDecl = ctx.getOptionalSomeDecl();
SILType optType = optAddr->getType();
SILType objType = optType.getOptionalObjectType();
if (accessType != AccessType::Set) {
// We're getting (or modifying), so we need to unwrap the optional.
auto int1Type = SILType::getBuiltinIntegerType(1, ctx);
auto falseLiteral = builder.createIntegerLiteral(loc, int1Type, false);
auto trueLiteral = builder.createIntegerLiteral(loc, int1Type, true);
auto isNil = builder.createSelectEnumAddr(loc, optAddr, int1Type, SILValue(), {
{noneDecl, trueLiteral}, {someDecl, falseLiteral}
});
builder.createCondFail(loc, isNil, "unexpectedly found nil while "
"unwrapping an Optional key-path expression");
}
switch (accessType) {
case AccessType::Get: {
// We have to copy the optional, since unwrapping is destructive.
auto tempAddr = builder.createAllocStack(loc, optType);
builder.createCopyAddr(loc, optAddr, tempAddr, IsNotTake, IsInitialization);
// Unwrap the optional.
auto objAddr = builder.createUncheckedTakeEnumDataAddr(loc, tempAddr, someDecl, objType);
callback(objAddr);
builder.createDestroyAddr(loc, objAddr);
builder.createDeallocStack(loc, tempAddr);
break;
}
case AccessType::Set: {
// Write the new value directly into optAddr.
auto objAddr = builder.createInitEnumDataAddr(loc, optAddr, someDecl, objType);
callback(objAddr);
// Finish creating the enum.
builder.createInjectEnumAddr(loc, optAddr, someDecl);
break;
}
case AccessType::Modify: {
// We have to copy the old value out, perform the modification,
// and copy the new value back in.
auto objAddr = builder.createAllocStack(loc, objType);
// Unwrap the optional and copy it to the new buffer.
auto unwrappedAddr = builder.createUncheckedTakeEnumDataAddr(loc, optAddr, someDecl, objType);
builder.createCopyAddr(loc, unwrappedAddr, objAddr, IsTake, IsInitialization);
callback(objAddr);
auto initAddr = builder.createInitEnumDataAddr(loc, optAddr, someDecl, objType);
builder.createCopyAddr(loc, objAddr, initAddr, IsTake, IsInitialization);
builder.createDeallocStack(loc, objAddr);
builder.createInjectEnumAddr(loc, optAddr, someDecl);
break;
}
}
});
}
};
class OptionalChainProjector : public ComponentProjector {
public:
OptionalChainProjector(const KeyPathPatternComponent &component,
std::unique_ptr<KeyPathProjector> parent,
BeginAccessInst *&beginAccess,
SILValue optionalChainResult,
SILLocation loc, SILBuilder &builder)
: ComponentProjector(component, std::move(parent), loc, builder),
optionalChainResult(optionalChainResult), beginAccess(beginAccess) {}
void project(AccessType accessType,
std::function<void(SILValue addr)> callback) override {
assert(component.getKind() ==
KeyPathPatternComponent::Kind::OptionalChain);
assert(accessType == AccessType::Get &&
"Optional chain components are immutable");
parent->project(accessType, [&](SILValue optAddr) {
auto &ctx = builder.getASTContext();
auto noneDecl = ctx.getOptionalNoneDecl();
auto someDecl = ctx.getOptionalSomeDecl();
SILType optType = optAddr->getType();
SILType objType = optType.getOptionalObjectType();
// Continue projecting only if the optional is non-nil
// i.e. if let objAddr = optAddr {
auto continuation = builder.splitBlockForFallthrough();
auto ifSome = builder.getFunction().createBasicBlockAfter(builder.getInsertionBB());
auto ifNone = builder.getFunction().createBasicBlockAfter(ifSome);
builder.createSwitchEnumAddr(loc, optAddr, /*defaultBB*/ nullptr,
{{noneDecl, ifNone}, {someDecl, ifSome}});
assert(ifSome->empty());
builder.setInsertionPoint(ifSome);
// We have to copy the optional, since unwrapping is destructive.
auto tempAddr = builder.createAllocStack(loc, optType);
builder.createCopyAddr(loc, optAddr, tempAddr, IsNotTake, IsInitialization);
// Unwrap the optional.
auto objAddr = builder.createUncheckedTakeEnumDataAddr(loc, tempAddr, someDecl, objType);
BeginAccessInst *origBeginAccess = beginAccess;
// at the end of the projection, callback will store a value in optionalChainResult
callback(objAddr);
builder.createDestroyAddr(loc, objAddr);
builder.createDeallocStack(loc, tempAddr);
builder.createBranch(loc, continuation);
// else, store nil in the result
builder.setInsertionPoint(ifNone);
// If the sub-projection ended the access in the some-branch, we also
// have to end the access in the none-branch.
if (origBeginAccess && origBeginAccess != beginAccess)
builder.createEndAccess(loc, origBeginAccess, /*aborted*/ false);
builder.createInjectEnumAddr(loc, optionalChainResult, noneDecl);
builder.createBranch(loc, continuation);
// end if, allow parents to clean up regardless of whether the chain continued
builder.setInsertionPoint(continuation, continuation->begin());
});
}
private:
SILValue optionalChainResult;
BeginAccessInst *&beginAccess;
};
/// A projector to handle a complete key path.
class CompleteKeyPathProjector : public KeyPathProjector {
public:
CompleteKeyPathProjector(KeyPathInst *keyPath, SILValue root,
SILLocation loc, SILBuilder &builder)
: KeyPathProjector(loc, builder), keyPath(keyPath), root(root) {}
void project(AccessType accessType,
std::function<void (SILValue)> callback) override {
auto components = keyPath->getPattern()->getComponents();
// Check if the keypath has an optional chain.
bool isOptionalChain = false;
for (const KeyPathPatternComponent &comp : components) {
if (comp.getKind() == KeyPathPatternComponent::Kind::OptionalChain) {
isOptionalChain = true;
break;
}
}
// Root projector
auto rootProjector = std::make_unique<RootProjector>(root, loc, builder);
BeginAccessInst *beginAccess = nullptr;
if (isOptionalChain) {
assert(accessType == AccessType::Get && "Optional chains are read-only");
// If we're reading an optional chain, create an optional result.
auto resultCanType = components.back().getComponentType();
auto &function = builder.getFunction();
auto substType =
resultCanType.subst(keyPath->getSubstitutions(), llvm::None);
auto optType = function.getLoweredType(
Lowering::AbstractionPattern::getOpaque(), substType);
assert(optType.getOptionalObjectType() &&
"Optional-chained key path should result in an optional");
SILValue optionalChainResult = builder.createAllocStack(loc, optType);
// Get the (conditional) result projector.
auto projector = create(0, std::move(rootProjector),
beginAccess, optionalChainResult);
projector->project(accessType, [&](SILValue result) {
// This will only run if all optional chains succeeded.
// Store the result in optionalChainResult.
builder.createCopyAddr(loc, result, optionalChainResult,
IsNotTake, IsInitialization);
});
// If the optional chain succeeded, optionalChainResult will have
// .some(result). Otherwise, projectOptionalChain will have written .none.
callback(optionalChainResult);
builder.createDestroyAddr(loc, optionalChainResult);
builder.createDeallocStack(loc, optionalChainResult);
} else {
// If we're not optional chaining, or we're writing to an optional chain,
// we don't need an optional result.
auto projector = create(0, std::move(rootProjector),
beginAccess, /*optionalChainResult*/ nullptr);
projector->project(accessType, callback);
}
assert(beginAccess == nullptr &&
"key path projector returned with dangling access enforcement");
}
bool isStruct() override {
auto components = keyPath->getPattern()->getComponents();
auto resultType = components.back().getComponentType();
return resultType.getStructOrBoundGenericStruct() != nullptr;
}
private:
KeyPathInst *keyPath;
SILValue root;
/// Recursively creates a chain of key path projectors
/// for components from index..<components.end()
std::unique_ptr<KeyPathProjector>
create(size_t index, std::unique_ptr<KeyPathProjector> parent,
BeginAccessInst *&beginAccess, SILValue optionalChainResult) {
auto components = keyPath->getPattern()->getComponents();
if (index >= components.size()) return parent;
auto &comp = components[index];
std::unique_ptr<KeyPathProjector> projector;
// Create a projector for this component.
switch (comp.getKind()) {
case KeyPathPatternComponent::Kind::StoredProperty:
projector = std::make_unique<StoredPropertyProjector>
(comp, std::move(parent), beginAccess, loc, builder);
break;
case KeyPathPatternComponent::Kind::TupleElement:
projector = std::make_unique<TupleElementProjector>
(comp, std::move(parent), loc, builder);
break;
case KeyPathPatternComponent::Kind::GettableProperty:
projector = std::make_unique<GettablePropertyProjector>
(keyPath, comp, std::move(parent), keyPath->getSubstitutions(),
beginAccess, loc, builder);
break;
case KeyPathPatternComponent::Kind::SettableProperty:
projector = std::make_unique<SettablePropertyProjector>
(keyPath, comp, std::move(parent), keyPath->getSubstitutions(),
beginAccess, loc, builder);
break;
case KeyPathPatternComponent::Kind::OptionalWrap:
projector = std::make_unique<OptionalWrapProjector>
(keyPath, comp, std::move(parent), loc, builder);
break;
case KeyPathPatternComponent::Kind::OptionalForce:
projector = std::make_unique<OptionalForceProjector>
(comp, std::move(parent), loc, builder);
break;
case KeyPathPatternComponent::Kind::OptionalChain:
projector = std::make_unique<OptionalChainProjector>
(comp, std::move(parent), beginAccess, optionalChainResult, loc,
builder);
break;
}
// Project the rest of the chain on top of this component.
return create(index + 1, std::move(projector),
beginAccess, optionalChainResult);
}
};
KeyPathInst *
KeyPathProjector::getLiteralKeyPath(SILValue keyPath) {
if (auto *upCast = dyn_cast<UpcastInst>(keyPath))
keyPath = upCast->getOperand();
// TODO: Look through other conversions, copies, etc.?
return dyn_cast<KeyPathInst>(keyPath);
}
std::unique_ptr<KeyPathProjector>
KeyPathProjector::create(SILValue keyPath, SILValue root,
SILLocation loc, SILBuilder &builder) {
// Is it a keypath instruction at all?
auto *kpInst = getLiteralKeyPath(keyPath);
if (!kpInst || !kpInst->hasPattern())
return nullptr;
// Check if the keypath only contains patterns which we support.
auto components = kpInst->getPattern()->getComponents();
for (const KeyPathPatternComponent &comp : components) {
if (comp.getKind() == KeyPathPatternComponent::Kind::GettableProperty ||
comp.getKind() == KeyPathPatternComponent::Kind::SettableProperty) {
if (!comp.getExternalSubstitutions().empty() ||
!comp.getSubscriptIndices().empty()) {
// TODO: right now we can't optimize computed properties that require
// additional context for subscript indices or generic environment
// See https://github.com/apple/swift/pull/28799#issuecomment-570299845
return nullptr;
}
}
}
return std::make_unique<CompleteKeyPathProjector>(kpInst, root,
loc, builder);
}