-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathArrayElementValuePropagation.cpp
383 lines (325 loc) · 12.3 KB
/
ArrayElementValuePropagation.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
//===--- ArrayElementValuePropagation.cpp - Propagate values of arrays ----===//
//
// 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
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "array-element-propagation"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SILOptimizer/Analysis/ArraySemantic.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "llvm/ADT/SmallVector.h"
using namespace swift;
/// Propagate the elements of array values to calls of the array's get_element
/// method, and replace calls of append(contentsOf:) with append(element:).
///
/// Array literal construction and array initialization of array values
/// associates element values with the array value. These values can be
/// propagated to the get_element method if we can prove that the array value
/// has not changed until reading the array value's element. These values can
/// also be used to replace append(contentsOf:) with multiple append(element:)
/// calls.
///
/// Propagation of the elements of one array allocation.
///
/// We propagate the elements associated with calls of
///
/// * Array.init(count:repeatedValue:)
/// The 'repeatedValue'.
/// TODO: this is not yet implemented.
///
/// * Array._adoptStorage(storage:count:)
/// The stores on the returned array element buffer pointer.
///
namespace {
/// Utility class for analysis array literal initializations.
///
/// Array literals are initialized by allocating an array buffer, and storing
/// the elements into it.
/// This class analysis all the code which does the array literal
/// initialization. It also collects uses of the array, like getElement calls
/// and append(contentsOf) calls.
class ArrayAllocation {
/// The array value returned by the allocation call.
SILValue ArrayValue;
/// The calls to Array get_element that use this array allocation.
llvm::SmallSetVector<ApplyInst *, 16> GetElementCalls;
/// The calls to Array append_contentsOf that use this array allocation.
llvm::SmallVector<ApplyInst *, 4> AppendContentsOfCalls;
/// A map of Array indices to element values
llvm::DenseMap<uint64_t, SILValue> ElementValueMap;
bool mapInitializationStores(ArraySemanticsCall arrayUninitCall);
bool recursivelyCollectUses(ValueBase *Def);
bool replacementsAreValid();
// After approx. this many elements, it's faster to use append(contentsOf:)
static constexpr unsigned APPEND_CONTENTSOF_REPLACEMENT_VALUES_MAX = 6;
public:
ArrayAllocation() {}
/// Analyzes an array allocation call.
///
/// Returns true if \p Alloc is the allocation of an array literal (or a
/// similar pattern) and the array values can be used to replace get_element
/// or append(contentof) calls.
bool analyze(ApplyInst *Alloc);
/// Replace getElement calls with the actual values.
bool replaceGetElements();
/// Replace append(contentsOf:) with multiple append(element:)
bool replaceAppendContentOf();
};
/// Map the indices of array element initialization stores to their values.
bool ArrayAllocation::mapInitializationStores(
ArraySemanticsCall arrayUninitCall) {
llvm::DenseMap<uint64_t, StoreInst *> elementStoreMap;
if (!arrayUninitCall.mapInitializationStores(elementStoreMap))
return false;
// Extract the SIL values of the array elements from the stores.
ElementValueMap.grow(elementStoreMap.size());
for (auto keyValue : elementStoreMap)
ElementValueMap[keyValue.getFirst()] = keyValue.getSecond()->getSrc();
return true;
}
bool ArrayAllocation::replacementsAreValid() {
unsigned ElementCount = ElementValueMap.size();
if (ElementCount > APPEND_CONTENTSOF_REPLACEMENT_VALUES_MAX)
return false;
// Bail if elements aren't contiguous
for (unsigned i = 0; i < ElementCount; ++i)
if (!ElementValueMap.count(i))
return false;
return true;
}
/// Recursively look at all uses of this definition. Abort if the array value
/// could escape or be changed. Collect all uses that are calls to array.count.
bool ArrayAllocation::recursivelyCollectUses(ValueBase *Def) {
LLVM_DEBUG(llvm::dbgs() << "Collecting uses of:");
LLVM_DEBUG(Def->dump());
for (auto *Opd : Def->getUses()) {
auto *User = Opd->getUser();
// Ignore reference counting and debug instructions.
if (isa<RefCountingInst>(User) || isa<DebugValueInst>(User) ||
isa<DestroyValueInst>(User) || isa<EndBorrowInst>(User))
continue;
if (auto *CVI = dyn_cast<CopyValueInst>(User)) {
if (!recursivelyCollectUses(CVI))
return false;
continue;
}
if (auto *BBI = dyn_cast<BeginBorrowInst>(User)) {
if (!recursivelyCollectUses(BBI))
return false;
continue;
}
// Array value projection.
if (auto *SEI = dyn_cast<StructExtractInst>(User)) {
if (!recursivelyCollectUses(SEI))
return false;
continue;
}
if (auto *MDI = dyn_cast<MarkDependenceInst>(User)) {
if (Def != MDI->getBase())
return false;
continue;
}
// Check array semantic calls.
ArraySemanticsCall ArrayOp(User);
switch (ArrayOp.getKind()) {
case ArrayCallKind::kNone:
return false;
case ArrayCallKind::kAppendContentsOf:
AppendContentsOfCalls.push_back(ArrayOp);
break;
case ArrayCallKind::kGetElement:
GetElementCalls.insert(ArrayOp);
break;
case ArrayCallKind::kArrayFinalizeIntrinsic:
if (!recursivelyCollectUses(cast<SingleValueInstruction>(User)))
return false;
break;
default:
if (ArrayOp.doesNotChangeArray())
break;
return false;
}
}
return true;
}
bool ArrayAllocation::analyze(ApplyInst *Alloc) {
GetElementCalls.clear();
AppendContentsOfCalls.clear();
ElementValueMap.clear();
ArraySemanticsCall Uninitialized(Alloc, "array.uninitialized");
if (!Uninitialized)
return false;
LLVM_DEBUG(llvm::dbgs() << "Found array allocation: ");
LLVM_DEBUG(Alloc->dump());
ArrayValue = Uninitialized.getArrayValue();
if (!ArrayValue) {
LLVM_DEBUG(llvm::dbgs() << "Did not find array value\n");
return false;
}
LLVM_DEBUG(llvm::dbgs() << "ArrayValue: ");
LLVM_DEBUG(ArrayValue->dump());
// Figure out all stores to the array.
if (!mapInitializationStores(Uninitialized)) {
LLVM_DEBUG(llvm::dbgs() << "Could not map initializing stores\n");
return false;
}
// Check if the array value was stored or has escaped.
if (!recursivelyCollectUses(ArrayValue)) {
LLVM_DEBUG(llvm::dbgs() << "Array value stored or escaped\n");
return false;
}
return true;
}
/// Replace getElement calls with the actual values.
///
/// \code
/// store %x to %element_address
/// ...
/// %e = apply %getElement(%array, %constant_index)
/// \endcode
/// The value %e is replaced with %x.
bool ArrayAllocation::replaceGetElements() {
bool Changed = false;
for (auto *GetElementCall : GetElementCalls) {
ArraySemanticsCall GetElement(GetElementCall);
assert(GetElement.getKind() == ArrayCallKind::kGetElement);
auto ConstantIndex = GetElement.getConstantIndex();
if (ConstantIndex == llvm::None)
continue;
// ElementValueMap keys are unsigned. Avoid implicit signed-unsigned
// conversion from an invalid index to a valid index.
if (*ConstantIndex < 0)
continue;
auto EltValueIt = ElementValueMap.find(*ConstantIndex);
if (EltValueIt == ElementValueMap.end())
continue;
Changed |= GetElement.replaceByValue(EltValueIt->second);
}
return Changed;
}
/// Replace append(contentsOf:) with multiple append(element:)
///
/// \code
/// store %x to %source_array_element_address_0
/// store %y to %source_array_element_address_1
/// ...
/// apply %append_contentsOf(%dest_array, %source_array)
/// \endcode
/// is replaced by
/// \code
/// store %x to %source_array_element_address_0
/// store %y to %source_array_element_address_1
/// ...
/// apply %reserveCapacityForAppend(%dest_array, %number_of_values)
/// apply %append_element(%dest_array, %x)
/// apply %append_element(%dest_array, %y)
/// ...
/// \endcode
/// The source_array and its initialization code can then be deleted (if not
/// used otherwise).
bool ArrayAllocation::replaceAppendContentOf() {
if (AppendContentsOfCalls.empty())
return false;
if (ElementValueMap.empty())
return false;
// Check if there is a store to each element.
if (!replacementsAreValid())
return false;
llvm::SmallVector<SILValue, 4> ElementValueVector;
for (unsigned i = 0; i < ElementValueMap.size(); ++i) {
SILValue V = ElementValueMap[i];
ElementValueVector.push_back(V);
}
SILFunction *Fn = AppendContentsOfCalls[0]->getFunction();
SILModule &M = Fn->getModule();
ASTContext &Ctx = M.getASTContext();
LLVM_DEBUG(llvm::dbgs() << "Array append contentsOf calls replaced in "
<< Fn->getName() << "\n");
// Get the needed Array helper functions.
FuncDecl *AppendFnDecl = Ctx.getArrayAppendElementDecl();
if (!AppendFnDecl)
return false;
FuncDecl *ReserveFnDecl = Ctx.getArrayReserveCapacityDecl();
if (!ReserveFnDecl)
return false;
auto Mangled = SILDeclRef(AppendFnDecl, SILDeclRef::Kind::Func).mangle();
SILFunction *AppendFn = M.loadFunction(Mangled,
SILModule::LinkingMode::LinkAll);
if (!AppendFn)
return false;
Mangled = SILDeclRef(ReserveFnDecl, SILDeclRef::Kind::Func).mangle();
SILFunction *ReserveFn = M.loadFunction(Mangled,
SILModule::LinkingMode::LinkAll);
if (!ReserveFn)
return false;
bool Changed = false;
// Usually there is only a single append(contentsOf:) call. But there might
// be multiple - with the same source array to append.
for (ApplyInst *AppendContentOfCall : AppendContentsOfCalls) {
ArraySemanticsCall AppendContentsOf(AppendContentOfCall);
assert(AppendContentsOf && "Must be AppendContentsOf call");
// In case if it's not an Array, but e.g. an ContiguousArray
if (!AppendContentsOf.getSelf()->getType().getASTType()->isArray())
continue;
SILType ArrayType = ArrayValue->getType();
auto *NTD = ArrayType.getASTType()->getAnyNominal();
SubstitutionMap ArraySubMap = ArrayType.getASTType()
->getContextSubstitutionMap(M.getSwiftModule(), NTD);
AppendContentsOf.replaceByAppendingValues(AppendFn, ReserveFn,
ElementValueVector,
ArraySubMap);
Changed = true;
}
return Changed;
}
// =============================================================================
// Driver
// =============================================================================
class ArrayElementPropagation : public SILFunctionTransform {
public:
ArrayElementPropagation() {}
void run() override {
auto &Fn = *getFunction();
bool Changed = false;
LLVM_DEBUG(llvm::dbgs() << "ArrayElementPropagation looking at function: "
<< Fn.getName() << "\n");
for (auto &BB : Fn) {
for (auto &Inst : BB) {
if (auto *Apply = dyn_cast<ApplyInst>(&Inst)) {
ArrayAllocation ALit;
if (!ALit.analyze(Apply))
continue;
// First optimization: replace getElement calls.
if (ALit.replaceGetElements()) {
Changed = true;
// Re-do the analysis if the SIL changed.
if (!ALit.analyze(Apply))
continue;
}
// Second optimization: replace append(contentsOf:) calls.
Changed |= ALit.replaceAppendContentOf();
}
}
}
if (Changed) {
PM->invalidateAnalysis(
&Fn, SILAnalysis::InvalidationKind::CallsAndInstructions);
}
}
};
} // end anonymous namespace
SILTransform *swift::createArrayElementPropagation() {
return new ArrayElementPropagation();
}