-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathRefCountState.h
446 lines (360 loc) · 17.2 KB
/
RefCountState.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
//===--- RefCountState.h - Represents a Reference Count ---------*- 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
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_SILOPTIMIZER_PASSMANAGER_ARC_REFCOUNTSTATE_H
#define SWIFT_SILOPTIMIZER_PASSMANAGER_ARC_REFCOUNTSTATE_H
#include "RCStateTransition.h"
#include "swift/Basic/BlotMapVector.h"
#include "swift/Basic/ImmutablePointerSet.h"
#include "swift/Basic/type_traits.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SILOptimizer/Analysis/ARCAnalysis.h"
#include "swift/SILOptimizer/Analysis/EpilogueARCAnalysis.h"
#include "swift/SILOptimizer/Analysis/RCIdentityAnalysis.h"
#include <algorithm>
namespace swift {
class AliasAnalysis;
} // end namespace swift
//===----------------------------------------------------------------------===//
// Ref Count State
//===----------------------------------------------------------------------===//
namespace swift {
/// A struct that abstracts over reference counts manipulated by strong_retain,
/// retain_value, strong_release,
class RefCountState {
protected:
/// Return the SILValue that represents the RCRoot that we are
/// tracking.
SILValue RCRoot;
/// The last state transition that this RefCountState went through. None if we
/// have not see any transition on this ref count yet.
RCStateTransition Transition;
/// Was the pointer we are tracking known incremented when we visited the
/// current increment we are tracking? In that case we know that it is safe
/// to move the inner retain over instructions that may decrement ref counts
/// since the outer retain will keep the reference counted value alive.
bool KnownSafe = false;
public:
RefCountState() = default;
~RefCountState() = default;
RefCountState(const RefCountState &) = default;
RefCountState &operator=(const RefCountState &) = default;
RefCountState(RefCountState &&) = default;
RefCountState &operator=(RefCountState &&) = default;
/// Initializes/reinitialized the state for I. If we reinitialize we return
/// true.
bool initWithMutatorInst(ImmutablePointerSet<SILInstruction> *I,
RCIdentityFunctionInfo *RCFI) {
assert(I->size() == 1);
// Are we already tracking a ref count modification?
bool Nested = isTrackingRefCount();
Transition = RCStateTransition(I);
assert(Transition.isMutator() && "Expected I to be a mutator!\n");
// Initialize KnownSafe to a conservative false value.
KnownSafe = false;
// Initialize value.
RCRoot = RCFI->getRCIdentityRoot((*I->begin())->getOperand(0));
return Nested;
}
/// Uninitialize the current state.
void clear() {
KnownSafe = false;
}
/// Is this ref count initialized and tracking a ref count ptr.
bool isTrackingRefCount() const { return Transition.isValid(); }
/// Are we tracking an instruction currently? This returns false when given an
/// uninitialized ReferenceCountState.
bool isTrackingRefCountInst() const {
return Transition.isValid() && Transition.isMutator();
}
/// Are we tracking a source of ref counts? This currently means that we are
/// tracking an argument that is @owned. In the future this will include
/// return values of functions that are @owned.
bool isTrackingRefCountSource() const {
return Transition.isValid() && Transition.isEndPoint();
}
/// Return the increment we are tracking.
RCStateTransition::mutator_range getInstructions() const {
return Transition.getMutators();
}
/// Returns true if I is in the instructions we are tracking.
bool containsInstruction(SILInstruction *I) const {
return Transition.isValid() && Transition.containsMutator(I);
}
/// Return the value with reference semantics that is the operand of our
/// increment.
SILValue getRCRoot() const {
assert(RCRoot && "Value should never be null here");
return RCRoot;
}
/// Returns true if we have a valid value that we are tracking.
bool hasRCRoot() const {
return (bool)RCRoot;
}
/// This retain is known safe if the operand we are tracking was already known
/// incremented previously. This occurs when you have nested increments.
bool isKnownSafe() const { return KnownSafe; }
/// Set KnownSafe to true if \p NewValue is true. If \p NewValue is false,
/// this is a no-op.
void updateKnownSafe(bool NewValue) {
KnownSafe |= NewValue;
}
void clearKnownSafe() { KnownSafe = false; }
};
//===----------------------------------------------------------------------===//
// Bottom Up Ref Count State
//===----------------------------------------------------------------------===//
class BottomUpRefCountState : public RefCountState {
public:
/// Sequence of states that a value with reference semantics can go through
/// when visiting decrements bottom up. The reason why I have this separate
/// from TopDownSubstruct is I think it gives more clarity to the algorithm by
/// giving it typed form.
enum class LatticeState {
None, ///< The pointer has no information associated with it.
Decremented, ///< The pointer will be decremented.
MightBeUsed, ///< The pointer will be used and then at this point
/// be decremented
MightBeDecremented, ///< The pointer might be decremented again implying
/// that we cannot, without being known safe remove
/// this decrement.
};
private:
using SuperTy = RefCountState;
/// Current place in the sequence of the value.
LatticeState LatState = LatticeState::None;
/// True if we have seen a NonARCUser of this instruction. This means bottom
/// up assuming we have this property as a meet over all paths property, we
/// know that all releases we see are known safe.
bool FoundNonARCUser = false;
public:
BottomUpRefCountState() = default;
~BottomUpRefCountState() = default;
BottomUpRefCountState(const BottomUpRefCountState &) = default;
BottomUpRefCountState &operator=(const BottomUpRefCountState &) = default;
BottomUpRefCountState(BottomUpRefCountState &&) = default;
BottomUpRefCountState &operator=(BottomUpRefCountState &&) = default;
/// Getter for LatticeState
LatticeState getLatticeState() const {return LatState;}
/// Return true if the release can be moved to the retain.
bool isCodeMotionSafe() const {
return LatState != LatticeState::MightBeDecremented;
}
/// Initializes/reinitialized the state for I. If we reinitialize we return
/// true.
bool initWithMutatorInst(ImmutablePointerSet<SILInstruction> *I,
RCIdentityFunctionInfo *RCFI);
/// Update this reference count's state given the instruction \p I.
void
updateForSameLoopInst(SILInstruction *I,
AliasAnalysis *AA);
/// Remove "KnownSafe" on the BottomUpRefCountState, if we find a retain
/// instruction with another RCIdentity can pair with the previously visited
/// retain instruction.
void checkAndResetKnownSafety(
SILInstruction *I, SILValue VisitedRC,
std::function<bool(SILInstruction *)> checkIfRefCountInstIsMatched,
RCIdentityFunctionInfo *RCIA, AliasAnalysis *AA);
/// Update this reference count's state given the instruction \p I.
//
/// The main difference in between this routine and update for same loop inst
/// is that if we see any decrements on a value, we treat it as being
/// guaranteed used. We treat any uses as regular uses.
/// This function is conservative enough that the flow sensitive nature of
/// loop summarized instructions does not matter.
void updateForDifferentLoopInst(
SILInstruction *I,
AliasAnalysis *AA);
/// Attempt to merge \p Other into this ref count state. Return true if we
/// succeed and false otherwise.
bool merge(const BottomUpRefCountState &Other);
/// Returns true if the passed in ref count inst matches the ref count inst
/// we are tracking. This handles generically retains/release.
bool isRefCountInstMatchedToTrackedInstruction(SILInstruction *RefCountInst);
/// Uninitialize the current state.
void clear();
void dump();
private:
/// Return true if we *might* remove this instruction.
///
/// This is a conservative query given the information we know, so as we
/// perform the dataflow it may change value.
bool mightRemoveMutators();
/// Can we guarantee that the given reference counted value has been modified?
bool isRefCountStateModified() const;
/// Returns true if given the current lattice state, do we care if the value
/// we are tracking is decremented.
bool valueCanBeDecrementedGivenLatticeState() const;
/// If advance the state's sequence appropriately for a decrement. If we do
/// advance return true. Otherwise return false.
bool handleDecrement();
/// Check if PotentialDecrement can decrement the reference count associated
/// with the value we are tracking. If so advance the state's sequence
/// appropriately and return true. Otherwise return false.
bool handlePotentialDecrement(SILInstruction *Decrement, AliasAnalysis *AA);
/// Returns true if given the current lattice state, do we care if the value
/// we are tracking is used.
bool valueCanBeUsedGivenLatticeState() const;
/// Given the current lattice state, if we have seen a use, advance the
/// lattice state. Return true if we do so and false otherwise.
bool handleUser();
/// Check if PotentialUser could be a use of the reference counted value that
/// requires user to be alive. If so advance the state's sequence
/// appropriately and return true. Otherwise return false.
bool
handlePotentialUser(SILInstruction *PotentialUser,
AliasAnalysis *AA);
/// Returns true if given the current lattice state, do we care if the value
/// we are tracking is used.
bool valueCanBeGuaranteedUsedGivenLatticeState() const;
/// Given the current lattice state, if we have seen a use, advance the
/// lattice state. Return true if we do so and false otherwise.
bool handleGuaranteedUser();
/// Check if PotentialGuaranteedUser can use the reference count associated
/// with the value we are tracking. If so advance the state's sequence
/// appropriately and return true. Otherwise return false.
bool handlePotentialGuaranteedUser(
SILInstruction *User,
AliasAnalysis *AA);
/// We have a matching ref count inst. Return true if we advance the sequence
/// and false otherwise.
bool handleRefCountInstMatch();
};
//===----------------------------------------------------------------------===//
// Top Down Ref Count State
//===----------------------------------------------------------------------===//
class TopDownRefCountState : public RefCountState {
public:
/// Sequence of states that a value with reference semantics can go through
/// when visiting decrements bottom up. The reason why I have this separate
/// from BottomUpRefCountState is I think it gives more clarity to the
/// algorithm by giving it typed form.
enum class LatticeState {
None, ///< The pointer has no information associated with it.
Incremented, ///< The pointer has been incremented.
MightBeDecremented, ///< The pointer has been incremented and might be
/// decremented. be decremented again implying
MightBeUsed, ///< The pointer has been incremented,
};
private:
using SuperTy = RefCountState;
/// Current place in the sequence of the value.
LatticeState LatState = LatticeState::None;
public:
TopDownRefCountState() = default;
~TopDownRefCountState() = default;
TopDownRefCountState(const TopDownRefCountState &) = default;
TopDownRefCountState &operator=(const TopDownRefCountState &) = default;
TopDownRefCountState(TopDownRefCountState &&) = default;
TopDownRefCountState &operator=(TopDownRefCountState &&) = default;
/// Getter for LatticeState
LatticeState getLatticeState() const {return LatState;}
/// Return true if the retain can be moved to the release.
bool isCodeMotionSafe() const {
return LatState != LatticeState::MightBeUsed;
}
/// Initializes/reinitialized the state for I. If we reinitialize we return
/// true.
bool initWithMutatorInst(ImmutablePointerSet<SILInstruction> *I,
RCIdentityFunctionInfo *RCFI);
/// Initialize the state given the consumed argument Arg.
void initWithArg(SILFunctionArgument *Arg);
/// Initialize this RefCountState with an instruction which introduces a new
/// ref count at +1.
void initWithEntranceInst(ImmutablePointerSet<SILInstruction> *I,
SILValue RCIdentity);
/// Uninitialize the current state.
void clear();
/// Update this reference count's state given the instruction \p I.
void
updateForSameLoopInst(SILInstruction *I,
AliasAnalysis *AA);
/// Remove "KnownSafe" on the TopDownRefCountState, if we find a retain
/// instruction with another RCIdentity can pair with the previously visited
/// retain instruction.
void checkAndResetKnownSafety(
SILInstruction *I, SILValue VisitedRC,
std::function<bool(SILInstruction *)> checkIfRefCountInstIsMatched,
RCIdentityFunctionInfo *RCIA, AliasAnalysis *AA);
/// Update this reference count's state given the instruction \p I.
///
/// The main difference in between this routine and update for same loop inst
/// is that if we see any decrements on a value, we treat it as being
/// guaranteed used. We treat any uses as regular uses.
/// This function is conservative enough that the flow sensitive nature of
/// loop summarized instructions does not matter.
void updateForDifferentLoopInst(
SILInstruction *I,
AliasAnalysis *AA);
/// Returns true if the passed in ref count inst matches the ref count inst
/// we are tracking. This handles generically retains/release.
bool isRefCountInstMatchedToTrackedInstruction(SILInstruction *RefCountInst);
/// Attempt to merge \p Other into this ref count state. Return true if we
/// succeed and false otherwise.
bool merge(const TopDownRefCountState &Other);
void dump();
private:
/// Can we guarantee that the given reference counted value has been modified?
bool isRefCountStateModified() const;
/// Returns true if given the current lattice state, do we care if the value
/// we are tracking is decremented.
bool valueCanBeDecrementedGivenLatticeState() const;
/// If advance the state's sequence appropriately for a decrement. If we do
/// advance return true. Otherwise return false.
bool handleDecrement();
/// Check if PotentialDecrement can decrement the reference count associated
/// with the value we are tracking. If so advance the state's sequence
/// appropriately and return true. Otherwise return false.
bool handlePotentialDecrement(
SILInstruction *PotentialDecrement,
AliasAnalysis *AA);
/// Returns true if given the current lattice state, do we care if the value
/// we are tracking is used.
bool valueCanBeUsedGivenLatticeState() const;
/// Given the current lattice state, if we have seen a use, advance the
/// lattice state. Return true if we do so and false otherwise.
bool handleUser();
/// Check if PotentialUser could be a use of the reference counted value that
/// requires user to be alive. If so advance the state's sequence
/// appropriately and return true. Otherwise return false.
bool handlePotentialUser(SILInstruction *PotentialUser, AliasAnalysis *AA);
/// Returns true if given the current lattice state, do we care if the value
/// we are tracking is used.
bool valueCanBeGuaranteedUsedGivenLatticeState() const;
/// Given the current lattice state, if we have seen a use, advance the
/// lattice state. Return true if we do so and false otherwise.
bool handleGuaranteedUser();
/// Check if PotentialGuaranteedUser can use the reference count associated
/// with the value we are tracking. If so advance the state's sequence
/// appropriately and return true. Otherwise return false.
bool handlePotentialGuaranteedUser(
SILInstruction *PotentialGuaranteedUser,
AliasAnalysis *AA);
/// We have a matching ref count inst. Return true if we advance the sequence
/// and false otherwise.
bool handleRefCountInstMatch();
};
// These static asserts are here for performance reasons.
static_assert(IsTriviallyCopyable<BottomUpRefCountState>::value,
"All ref count states must be trivially copyable");
static_assert(IsTriviallyCopyable<TopDownRefCountState>::value,
"All ref count states must be trivially copyable");
} // end swift namespace
namespace llvm {
raw_ostream &operator<<(raw_ostream &OS,
swift::BottomUpRefCountState::LatticeState S);
raw_ostream &operator<<(raw_ostream &OS,
swift::TopDownRefCountState::LatticeState S);
} // end namespace llvm
#endif