forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObjectOutliner.cpp
571 lines (501 loc) · 21 KB
/
ObjectOutliner.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
//===--- ObjectOutliner.cpp - Outline heap objects -----------------------===//
//
// 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 "objectoutliner"
#include "swift/AST/ASTMangler.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "llvm/Support/Debug.h"
using namespace swift;
namespace {
class ObjectOutliner {
SILOptFunctionBuilder &FunctionBuilder;
NominalTypeDecl *ArrayDecl = nullptr;
int GlobIdx = 0;
// Instructions to be deleted.
llvm::SmallVector<SILInstruction *, 4> ToRemove;
bool isCOWType(SILType type) {
return type.getNominalOrBoundGenericNominal() == ArrayDecl;
}
bool isValidUseOfObject(SILInstruction *Val,
bool isCOWObject,
ApplyInst **FindStringCall = nullptr);
bool getObjectInitVals(SILValue Val,
llvm::DenseMap<VarDecl *, StoreInst *> &MemberStores,
llvm::SmallVectorImpl<StoreInst *> &TailStores,
unsigned NumTailTupleElements,
ApplyInst **FindStringCall);
bool handleTailAddr(int TailIdx, SILInstruction *I, unsigned NumTailTupleElements,
llvm::SmallVectorImpl<StoreInst *> &TailStores);
bool optimizeObjectAllocation(AllocRefInst *ARI);
void replaceFindStringCall(ApplyInst *FindStringCall);
public:
ObjectOutliner(SILOptFunctionBuilder &FunctionBuilder,
NominalTypeDecl *ArrayDecl)
: FunctionBuilder(FunctionBuilder), ArrayDecl(ArrayDecl) { }
bool run(SILFunction *F);
};
bool ObjectOutliner::run(SILFunction *F) {
bool hasChanged = false;
for (auto &BB : *F) {
auto Iter = BB.begin();
while (Iter != BB.end()) {
SILInstruction *I = &*Iter;
Iter++;
if (auto *ARI = dyn_cast<AllocRefInst>(I)) {
unsigned GarbageSize = ToRemove.size();
// Try to replace the alloc_ref with a static object.
if (optimizeObjectAllocation(ARI)) {
hasChanged = true;
} else {
// No transformation was made. Restore the original state of the garbage list.
assert(GarbageSize <= ToRemove.size());
ToRemove.resize(GarbageSize);
}
}
}
// Delaying the deallocation of instructions avoids problems with iterator invalidation in the
// instruction loop above.
for (auto *I : ToRemove)
I->eraseFromParent();
ToRemove.clear();
}
return hasChanged;
}
/// Get all stored properties of a class, including it's super classes.
static void getFields(ClassDecl *Cl, SmallVectorImpl<VarDecl *> &Fields) {
if (ClassDecl *SuperCl = Cl->getSuperclassDecl()) {
getFields(SuperCl, Fields);
}
for (VarDecl *Field : Cl->getStoredProperties()) {
Fields.push_back(Field);
}
}
/// Check if \p V is a valid instruction for a static initializer, including
/// all its operands.
static bool isValidInitVal(SILValue V) {
if (auto I = dyn_cast<SingleValueInstruction>(V)) {
if (!SILGlobalVariable::isValidStaticInitializerInst(I, I->getModule()))
return false;
for (Operand &Op : I->getAllOperands()) {
if (!isValidInitVal(Op.get()))
return false;
}
return true;
}
return false;
}
/// Check if a use of an object may prevent outlining the object.
///
/// If \p isCOWObject is true, then the object reference is wrapped into a
/// COW container. Currently this is just Array<T>.
/// If a use is a call to the findStringSwitchCase semantic call, the apply
/// is returned in \p FindStringCall.
bool ObjectOutliner::isValidUseOfObject(SILInstruction *I, bool isCOWObject,
ApplyInst **FindStringCall) {
switch (I->getKind()) {
case SILInstructionKind::DebugValueAddrInst:
case SILInstructionKind::DebugValueInst:
case SILInstructionKind::LoadInst:
case SILInstructionKind::DeallocRefInst:
case SILInstructionKind::StrongRetainInst:
case SILInstructionKind::StrongReleaseInst:
case SILInstructionKind::FixLifetimeInst:
case SILInstructionKind::SetDeallocatingInst:
return true;
case SILInstructionKind::ReturnInst:
case SILInstructionKind::TryApplyInst:
case SILInstructionKind::PartialApplyInst:
case SILInstructionKind::StoreInst:
/// We don't have a representation for COW objects in SIL, so we do some
/// ad-hoc testing: We can ignore uses of a COW object if any use after
/// this will do a uniqueness checking before the object is modified.
return isCOWObject;
case SILInstructionKind::ApplyInst:
if (!isCOWObject)
return false;
// There should only be a single call to findStringSwitchCase. But even
// if there are multiple calls, it's not problem - we'll just optimize the
// last one we find.
if (cast<ApplyInst>(I)->hasSemantics("findStringSwitchCase"))
*FindStringCall = cast<ApplyInst>(I);
return true;
case SILInstructionKind::StructInst:
if (isCOWType(cast<StructInst>(I)->getType())) {
// The object is wrapped into a COW container.
isCOWObject = true;
}
break;
case SILInstructionKind::UncheckedRefCastInst:
case SILInstructionKind::StructElementAddrInst:
case SILInstructionKind::AddressToPointerInst:
assert(!isCOWObject && "instruction cannot have a COW object as operand");
break;
case SILInstructionKind::TupleInst:
case SILInstructionKind::TupleExtractInst:
case SILInstructionKind::EnumInst:
break;
case SILInstructionKind::StructExtractInst:
// To be on the safe side we don't consider the object as COW if it is
// extracted again from the COW container: the uniqueness check may be
// optimized away in this case.
isCOWObject = false;
break;
case SILInstructionKind::BuiltinInst: {
// Handle the case for comparing addresses. This occurs when the Array
// comparison function is inlined.
auto *BI = cast<BuiltinInst>(I);
BuiltinValueKind K = BI->getBuiltinInfo().ID;
if (K == BuiltinValueKind::ICMP_EQ || K == BuiltinValueKind::ICMP_NE)
return true;
if (K == BuiltinValueKind::DestroyArray) {
// We must not try to delete the tail allocated values. Although this would be a no-op
// (because we only handle trivial types), it would be semantically wrong to apply this
// builtin on the outlined object.
ToRemove.push_back(BI);
return true;
}
return false;
}
default:
return false;
}
auto SVI = cast<SingleValueInstruction>(I);
for (Operand *Use : getNonDebugUses(SVI)) {
if (!isValidUseOfObject(Use->getUser(), isCOWObject, FindStringCall))
return false;
}
return true;
}
/// Handle the address of a tail element.
bool ObjectOutliner::handleTailAddr(int TailIdx, SILInstruction *TailAddr,
unsigned NumTailTupleElements,
llvm::SmallVectorImpl<StoreInst *> &TailStores) {
if (NumTailTupleElements > 0) {
if (auto *TEA = dyn_cast<TupleElementAddrInst>(TailAddr)) {
unsigned TupleIdx = TEA->getFieldNo();
assert(TupleIdx < NumTailTupleElements);
for (Operand *Use : TEA->getUses()) {
if (!handleTailAddr(TailIdx * NumTailTupleElements + TupleIdx, Use->getUser(), 0,
TailStores))
return false;
}
return true;
}
} else {
if (TailIdx >= 0 && TailIdx < (int)TailStores.size()) {
if (auto *SI = dyn_cast<StoreInst>(TailAddr)) {
if (!isValidInitVal(SI->getSrc()) || TailStores[TailIdx])
return false;
TailStores[TailIdx] = SI;
return true;
}
}
}
return isValidUseOfObject(TailAddr, /*isCOWObject*/false);
}
/// Get the init values for an object's stored properties and its tail elements.
bool ObjectOutliner::getObjectInitVals(SILValue Val,
llvm::DenseMap<VarDecl *, StoreInst *> &MemberStores,
llvm::SmallVectorImpl<StoreInst *> &TailStores,
unsigned NumTailTupleElements,
ApplyInst **FindStringCall) {
for (Operand *Use : Val->getUses()) {
SILInstruction *User = Use->getUser();
if (auto *UC = dyn_cast<UpcastInst>(User)) {
// Upcast is transparent.
if (!getObjectInitVals(UC, MemberStores, TailStores, NumTailTupleElements, FindStringCall))
return false;
} else if (auto *REA = dyn_cast<RefElementAddrInst>(User)) {
// The address of a stored property.
for (Operand *ElemAddrUse : REA->getUses()) {
SILInstruction *ElemAddrUser = ElemAddrUse->getUser();
if (auto *SI = dyn_cast<StoreInst>(ElemAddrUser)) {
if (!isValidInitVal(SI->getSrc()) || MemberStores[REA->getField()])
return false;
MemberStores[REA->getField()] = SI;
} else if (!isValidUseOfObject(ElemAddrUser, /*isCOWObject*/false)) {
return false;
}
}
} else if (auto *RTA = dyn_cast<RefTailAddrInst>(User)) {
// The address of a tail element.
for (Operand *TailUse : RTA->getUses()) {
SILInstruction *TailUser = TailUse->getUser();
if (auto *IA = dyn_cast<IndexAddrInst>(TailUser)) {
// An index_addr yields the address of any tail element. Only if the
// second operand (the index) is an integer literal we can figure out
// which tail element is refereneced.
int TailIdx = -1;
if (auto *Index = dyn_cast<IntegerLiteralInst>(IA->getIndex()))
TailIdx = Index->getValue().getZExtValue();
for (Operand *IAUse : IA->getUses()) {
if (!handleTailAddr(TailIdx, IAUse->getUser(), NumTailTupleElements, TailStores))
return false;
}
// Without an index_addr it's the first tail element.
} else if (!handleTailAddr(/*TailIdx*/0, TailUser, NumTailTupleElements, TailStores)) {
return false;
}
}
} else if (!isValidUseOfObject(User, /*isCOWObject*/false, FindStringCall)) {
return false;
}
}
return true;
}
class GlobalVariableMangler : public Mangle::ASTMangler {
public:
std::string mangleOutlinedVariable(SILFunction *F, int &uniqueIdx) {
std::string GlobName;
do {
beginManglingWithoutPrefix();
appendOperator(F->getName());
appendOperator("Tv", Index(uniqueIdx++));
GlobName = finalize();
} while (F->getModule().lookUpGlobalVariable(GlobName));
return GlobName;
}
};
/// Try to convert an object allocation into a statically initialized object.
///
/// In general this works for any class, but in practice it will only kick in
/// for array buffer objects. The use cases are array literals in a function.
/// For example:
/// func getarray() -> [Int] {
/// return [1, 2, 3]
/// }
bool ObjectOutliner::optimizeObjectAllocation(AllocRefInst *ARI) {
if (ARI->isObjC())
return false;
// Check how many tail allocated elements are on the object.
ArrayRef<Operand> TailCounts = ARI->getTailAllocatedCounts();
SILType TailType;
unsigned NumTailElems = 0;
// We only support a single tail allocated arrays.
// Stdlib's tail allocated arrays don't have any side-effects in the
// constructor if the element type is trivial.
// TODO: also exclude custom tail allocated arrays which might have
// side-effects in the destructor.
if (TailCounts.size() != 1)
return false;
// The number of tail allocated elements must be constant.
if (auto *ILI = dyn_cast<IntegerLiteralInst>(TailCounts[0].get())) {
if (ILI->getValue().getActiveBits() > 20)
return false;
NumTailElems = ILI->getValue().getZExtValue();
TailType = ARI->getTailAllocatedTypes()[0];
} else {
return false;
}
SILType Ty = ARI->getType();
ClassDecl *Cl = Ty.getClassOrBoundGenericClass();
if (!Cl)
return false;
llvm::SmallVector<VarDecl *, 16> Fields;
getFields(Cl, Fields);
llvm::DenseMap<VarDecl *, StoreInst *> MemberStores;
// A store for each element of the tail allocated array. In case of a tuple, there is a store
// for each tuple element. For example, a 3 element array of 2-element tuples
// [ (i0, i1), (i2, i3), (i4, i5) ]
// results in following store instructions, collected in TailStores:
// [ store i0, store i1, store i2, store i3, store i4, store i5 ]
llvm::SmallVector<StoreInst *, 16> TailStores;
unsigned NumStores = NumTailElems;
unsigned NumTailTupleElems = 0;
if (auto Tuple = TailType.getAs<TupleType>()) {
NumTailTupleElems = Tuple->getNumElements();
if (NumTailTupleElems == 0)
return false;
NumStores *= NumTailTupleElems;
}
TailStores.resize(NumStores);
ApplyInst *FindStringCall = nullptr;
// Get the initialization stores of the object's properties and tail
// allocated elements. Also check if there are any "bad" uses of the object.
if (!getObjectInitVals(ARI, MemberStores, TailStores, NumTailTupleElems, &FindStringCall))
return false;
// Is there a store for all the class properties?
if (MemberStores.size() != Fields.size())
return false;
// Is there a store for all tail allocated elements?
for (auto V : TailStores) {
if (!V)
return false;
}
LLVM_DEBUG(llvm::dbgs() << "Outline global variable in "
<< ARI->getFunction()->getName() << '\n');
SILModule *Module = &ARI->getFunction()->getModule();
// FIXME: Expansion
assert(!Cl->isResilient(Module->getSwiftModule(),
ResilienceExpansion::Minimal) &&
"constructor call of resilient class should prevent static allocation");
// Create a name for the outlined global variable.
GlobalVariableMangler Mangler;
std::string GlobName =
Mangler.mangleOutlinedVariable(ARI->getFunction(), GlobIdx);
SILGlobalVariable *Glob =
SILGlobalVariable::create(*Module, SILLinkage::Private, IsNotSerialized,
GlobName, ARI->getType());
// Schedule all init values for cloning into the initializer of Glob.
StaticInitCloner Cloner(Glob);
for (VarDecl *Field : Fields) {
StoreInst *MemberStore = MemberStores[Field];
Cloner.add(cast<SingleValueInstruction>(MemberStore->getSrc()));
}
for (StoreInst *TailStore : TailStores) {
Cloner.add(cast<SingleValueInstruction>(TailStore->getSrc()));
}
// Create the class property initializers
llvm::SmallVector<SILValue, 16> ObjectArgs;
for (VarDecl *Field : Fields) {
StoreInst *MemberStore = MemberStores[Field];
assert(MemberStore);
ObjectArgs.push_back(Cloner.clone(
cast<SingleValueInstruction>(MemberStore->getSrc())));
ToRemove.push_back(MemberStore);
}
unsigned NumBaseElements = ObjectArgs.size();
// Create the initializers for the tail elements.
if (NumTailTupleElems == 0) {
// The non-tuple element case.
for (StoreInst *TailStore : TailStores) {
ObjectArgs.push_back(Cloner.clone(
cast<SingleValueInstruction>(TailStore->getSrc())));
ToRemove.push_back(TailStore);
}
} else {
// The elements are tuples: combine NumTailTupleElems elements from TailStores to a single tuple
// instruction.
for (unsigned EIdx = 0; EIdx < NumTailElems; EIdx++) {
SmallVector<SILValue, 8> TupleElems;
for (unsigned TIdx = 0; TIdx < NumTailTupleElems; TIdx++) {
StoreInst *TailStore = TailStores[EIdx * NumTailTupleElems + TIdx];
SILValue V = Cloner.clone(cast<SingleValueInstruction>(TailStore->getSrc()));
TupleElems.push_back(V);
ToRemove.push_back(TailStore);
}
auto *TI = Cloner.getBuilder().createTuple(ARI->getLoc(), TailType, TupleElems);
ObjectArgs.push_back(TI);
}
}
// Create the initializer for the object itself.
SILBuilder StaticInitBuilder(Glob);
StaticInitBuilder.createObject(ArtificialUnreachableLocation(),
ARI->getType(), ObjectArgs, NumBaseElements);
// Replace the alloc_ref by global_value + strong_retain instructions.
SILBuilder B(ARI);
GlobalValueInst *GVI = B.createGlobalValue(ARI->getLoc(), Glob);
B.createStrongRetain(ARI->getLoc(), GVI, B.getDefaultAtomicity());
llvm::SmallVector<Operand *, 8> Worklist(ARI->use_begin(), ARI->use_end());
while (!Worklist.empty()) {
auto *Use = Worklist.pop_back_val();
SILInstruction *User = Use->getUser();
switch (User->getKind()) {
case SILInstructionKind::SetDeallocatingInst:
// set_deallocating is a replacement for a strong_release. Therefore
// we have to insert a strong_release to balance the strong_retain which
// we inserted after the global_value instruction.
B.setInsertionPoint(User);
B.createStrongRelease(User->getLoc(), GVI, B.getDefaultAtomicity());
LLVM_FALLTHROUGH;
case SILInstructionKind::DeallocRefInst:
ToRemove.push_back(User);
break;
default:
Use->set(GVI);
}
}
if (FindStringCall && NumTailElems > 16) {
assert(&*std::next(ARI->getIterator()) != FindStringCall &&
"FindStringCall must not be the next instruction after ARI because "
"deleting it would invalidate the instruction iterator");
replaceFindStringCall(FindStringCall);
}
ToRemove.push_back(ARI);
return true;
}
/// Replaces a call to _findStringSwitchCase with a call to
/// _findStringSwitchCaseWithCache which builds a cache (e.g. a Dictionary) and
/// stores it into a global variable. Then subsequent calls to this function can
/// do a fast lookup using the cache.
void ObjectOutliner::replaceFindStringCall(ApplyInst *FindStringCall) {
// Find the replacement function in the swift stdlib.
SmallVector<ValueDecl *, 1> results;
SILModule *Module = &FindStringCall->getFunction()->getModule();
Module->getASTContext().lookupInSwiftModule("_findStringSwitchCaseWithCache",
results);
if (results.size() != 1)
return;
auto *FD = dyn_cast<FuncDecl>(results.front());
if (!FD)
return;
SILDeclRef declRef(FD, SILDeclRef::Kind::Func);
SILFunction *replacementFunc = FunctionBuilder.getOrCreateFunction(
FindStringCall->getLoc(), declRef, NotForDefinition);
SILFunctionType *FTy = replacementFunc->getLoweredFunctionType();
if (FTy->getNumParameters() != 3)
return;
SILType cacheType = FTy->getParameters()[2].getSILStorageType().getObjectType();
NominalTypeDecl *cacheDecl = cacheType.getNominalOrBoundGenericNominal();
if (!cacheDecl)
return;
// FIXME: Expansion
assert(!cacheDecl->isResilient(Module->getSwiftModule(),
ResilienceExpansion::Minimal));
SILType wordTy = cacheType.getFieldType(
cacheDecl->getStoredProperties().front(), *Module);
GlobalVariableMangler Mangler;
std::string GlobName =
Mangler.mangleOutlinedVariable(FindStringCall->getFunction(), GlobIdx);
// Create an "opaque" global variable which is passed as inout to
// _findStringSwitchCaseWithCache and into which the function stores the
// "cache".
SILGlobalVariable *CacheVar =
SILGlobalVariable::create(*Module, SILLinkage::Private, IsNotSerialized,
GlobName, cacheType);
SILLocation Loc = FindStringCall->getLoc();
SILBuilder StaticInitBuilder(CacheVar);
auto *Zero = StaticInitBuilder.createIntegerLiteral(Loc, wordTy, 0);
StaticInitBuilder.createStruct(ArtificialUnreachableLocation(), cacheType,
{Zero, Zero});
SILBuilder B(FindStringCall);
GlobalAddrInst *CacheAddr = B.createGlobalAddr(FindStringCall->getLoc(),
CacheVar);
FunctionRefInst *FRI = B.createFunctionRef(FindStringCall->getLoc(),
replacementFunc);
ApplyInst *NewCall = B.createApply(FindStringCall->getLoc(), FRI,
FindStringCall->getSubstitutionMap(),
{ FindStringCall->getArgument(0),
FindStringCall->getArgument(1),
CacheAddr },
FindStringCall->isNonThrowing());
FindStringCall->replaceAllUsesWith(NewCall);
FindStringCall->eraseFromParent();
}
class ObjectOutlinerPass : public SILFunctionTransform {
void run() override {
SILFunction *F = getFunction();
SILOptFunctionBuilder FuncBuilder(*this);
ObjectOutliner Outliner(FuncBuilder,
F->getModule().getASTContext().getArrayDecl());
if (Outliner.run(F)) {
invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions);
}
}
};
} // end anonymous namespace
SILTransform *swift::createObjectOutliner() {
return new ObjectOutlinerPass();
}