/
ObjCARCOpts.cpp
2502 lines (2186 loc) · 90.9 KB
/
ObjCARCOpts.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
//===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This file defines ObjC ARC optimizations. ARC stands for Automatic
/// Reference Counting and is a system for managing reference counts for objects
/// in Objective C.
///
/// The optimizations performed include elimination of redundant, partially
/// redundant, and inconsequential reference count operations, elimination of
/// redundant weak pointer operations, and numerous minor simplifications.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
//
//===----------------------------------------------------------------------===//
#include "ARCRuntimeEntryPoints.h"
#include "BlotMapVector.h"
#include "DependencyAnalysis.h"
#include "ObjCARC.h"
#include "ProvenanceAnalysis.h"
#include "PtrState.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/EHPersonalities.h"
#include "llvm/Analysis/ObjCARCAliasAnalysis.h"
#include "llvm/Analysis/ObjCARCAnalysisUtils.h"
#include "llvm/Analysis/ObjCARCInstKind.h"
#include "llvm/Analysis/ObjCARCUtil.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/ObjCARC.h"
#include <cassert>
#include <iterator>
#include <utility>
using namespace llvm;
using namespace llvm::objcarc;
#define DEBUG_TYPE "objc-arc-opts"
static cl::opt<unsigned> MaxPtrStates("arc-opt-max-ptr-states",
cl::Hidden,
cl::desc("Maximum number of ptr states the optimizer keeps track of"),
cl::init(4095));
/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
/// @{
/// This is similar to GetRCIdentityRoot but it stops as soon
/// as it finds a value with multiple uses.
static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
// ConstantData (like ConstantPointerNull and UndefValue) is used across
// modules. It's never a single-use value.
if (isa<ConstantData>(Arg))
return nullptr;
if (Arg->hasOneUse()) {
if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
return FindSingleUseIdentifiedObject(BC->getOperand(0));
if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
if (GEP->hasAllZeroIndices())
return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
if (IsForwarding(GetBasicARCInstKind(Arg)))
return FindSingleUseIdentifiedObject(
cast<CallInst>(Arg)->getArgOperand(0));
if (!IsObjCIdentifiedObject(Arg))
return nullptr;
return Arg;
}
// If we found an identifiable object but it has multiple uses, but they are
// trivial uses, we can still consider this to be a single-use value.
if (IsObjCIdentifiedObject(Arg)) {
for (const User *U : Arg->users())
if (!U->use_empty() || GetRCIdentityRoot(U) != Arg)
return nullptr;
return Arg;
}
return nullptr;
}
/// @}
///
/// \defgroup ARCOpt ARC Optimization.
/// @{
// TODO: On code like this:
//
// objc_retain(%x)
// stuff_that_cannot_release()
// objc_autorelease(%x)
// stuff_that_cannot_release()
// objc_retain(%x)
// stuff_that_cannot_release()
// objc_autorelease(%x)
//
// The second retain and autorelease can be deleted.
// TODO: It should be possible to delete
// objc_autoreleasePoolPush and objc_autoreleasePoolPop
// pairs if nothing is actually autoreleased between them. Also, autorelease
// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
// after inlining) can be turned into plain release calls.
// TODO: Critical-edge splitting. If the optimial insertion point is
// a critical edge, the current algorithm has to fail, because it doesn't
// know how to split edges. It should be possible to make the optimizer
// think in terms of edges, rather than blocks, and then split critical
// edges on demand.
// TODO: OptimizeSequences could generalized to be Interprocedural.
// TODO: Recognize that a bunch of other objc runtime calls have
// non-escaping arguments and non-releasing arguments, and may be
// non-autoreleasing.
// TODO: Sink autorelease calls as far as possible. Unfortunately we
// usually can't sink them past other calls, which would be the main
// case where it would be useful.
// TODO: The pointer returned from objc_loadWeakRetained is retained.
// TODO: Delete release+retain pairs (rare).
STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
STATISTIC(NumRets, "Number of return value forwarding "
"retain+autoreleases eliminated");
STATISTIC(NumRRs, "Number of retain+release paths eliminated");
STATISTIC(NumPeeps, "Number of calls peephole-optimized");
#ifndef NDEBUG
STATISTIC(NumRetainsBeforeOpt,
"Number of retains before optimization");
STATISTIC(NumReleasesBeforeOpt,
"Number of releases before optimization");
STATISTIC(NumRetainsAfterOpt,
"Number of retains after optimization");
STATISTIC(NumReleasesAfterOpt,
"Number of releases after optimization");
#endif
namespace {
/// Per-BasicBlock state.
class BBState {
/// The number of unique control paths from the entry which can reach this
/// block.
unsigned TopDownPathCount = 0;
/// The number of unique control paths to exits from this block.
unsigned BottomUpPathCount = 0;
/// The top-down traversal uses this to record information known about a
/// pointer at the bottom of each block.
BlotMapVector<const Value *, TopDownPtrState> PerPtrTopDown;
/// The bottom-up traversal uses this to record information known about a
/// pointer at the top of each block.
BlotMapVector<const Value *, BottomUpPtrState> PerPtrBottomUp;
/// Effective predecessors of the current block ignoring ignorable edges and
/// ignored backedges.
SmallVector<BasicBlock *, 2> Preds;
/// Effective successors of the current block ignoring ignorable edges and
/// ignored backedges.
SmallVector<BasicBlock *, 2> Succs;
public:
static const unsigned OverflowOccurredValue;
BBState() = default;
using top_down_ptr_iterator = decltype(PerPtrTopDown)::iterator;
using const_top_down_ptr_iterator = decltype(PerPtrTopDown)::const_iterator;
top_down_ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
top_down_ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
const_top_down_ptr_iterator top_down_ptr_begin() const {
return PerPtrTopDown.begin();
}
const_top_down_ptr_iterator top_down_ptr_end() const {
return PerPtrTopDown.end();
}
bool hasTopDownPtrs() const {
return !PerPtrTopDown.empty();
}
unsigned top_down_ptr_list_size() const {
return std::distance(top_down_ptr_begin(), top_down_ptr_end());
}
using bottom_up_ptr_iterator = decltype(PerPtrBottomUp)::iterator;
using const_bottom_up_ptr_iterator =
decltype(PerPtrBottomUp)::const_iterator;
bottom_up_ptr_iterator bottom_up_ptr_begin() {
return PerPtrBottomUp.begin();
}
bottom_up_ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
const_bottom_up_ptr_iterator bottom_up_ptr_begin() const {
return PerPtrBottomUp.begin();
}
const_bottom_up_ptr_iterator bottom_up_ptr_end() const {
return PerPtrBottomUp.end();
}
bool hasBottomUpPtrs() const {
return !PerPtrBottomUp.empty();
}
unsigned bottom_up_ptr_list_size() const {
return std::distance(bottom_up_ptr_begin(), bottom_up_ptr_end());
}
/// Mark this block as being an entry block, which has one path from the
/// entry by definition.
void SetAsEntry() { TopDownPathCount = 1; }
/// Mark this block as being an exit block, which has one path to an exit by
/// definition.
void SetAsExit() { BottomUpPathCount = 1; }
/// Attempt to find the PtrState object describing the top down state for
/// pointer Arg. Return a new initialized PtrState describing the top down
/// state for Arg if we do not find one.
TopDownPtrState &getPtrTopDownState(const Value *Arg) {
return PerPtrTopDown[Arg];
}
/// Attempt to find the PtrState object describing the bottom up state for
/// pointer Arg. Return a new initialized PtrState describing the bottom up
/// state for Arg if we do not find one.
BottomUpPtrState &getPtrBottomUpState(const Value *Arg) {
return PerPtrBottomUp[Arg];
}
/// Attempt to find the PtrState object describing the bottom up state for
/// pointer Arg.
bottom_up_ptr_iterator findPtrBottomUpState(const Value *Arg) {
return PerPtrBottomUp.find(Arg);
}
void clearBottomUpPointers() {
PerPtrBottomUp.clear();
}
void clearTopDownPointers() {
PerPtrTopDown.clear();
}
void InitFromPred(const BBState &Other);
void InitFromSucc(const BBState &Other);
void MergePred(const BBState &Other);
void MergeSucc(const BBState &Other);
/// Compute the number of possible unique paths from an entry to an exit
/// which pass through this block. This is only valid after both the
/// top-down and bottom-up traversals are complete.
///
/// Returns true if overflow occurred. Returns false if overflow did not
/// occur.
bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
if (TopDownPathCount == OverflowOccurredValue ||
BottomUpPathCount == OverflowOccurredValue)
return true;
unsigned long long Product =
(unsigned long long)TopDownPathCount*BottomUpPathCount;
// Overflow occurred if any of the upper bits of Product are set or if all
// the lower bits of Product are all set.
return (Product >> 32) ||
((PathCount = Product) == OverflowOccurredValue);
}
// Specialized CFG utilities.
using edge_iterator = SmallVectorImpl<BasicBlock *>::const_iterator;
edge_iterator pred_begin() const { return Preds.begin(); }
edge_iterator pred_end() const { return Preds.end(); }
edge_iterator succ_begin() const { return Succs.begin(); }
edge_iterator succ_end() const { return Succs.end(); }
void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
bool isExit() const { return Succs.empty(); }
};
} // end anonymous namespace
const unsigned BBState::OverflowOccurredValue = 0xffffffff;
namespace llvm {
raw_ostream &operator<<(raw_ostream &OS,
BBState &BBState) LLVM_ATTRIBUTE_UNUSED;
} // end namespace llvm
void BBState::InitFromPred(const BBState &Other) {
PerPtrTopDown = Other.PerPtrTopDown;
TopDownPathCount = Other.TopDownPathCount;
}
void BBState::InitFromSucc(const BBState &Other) {
PerPtrBottomUp = Other.PerPtrBottomUp;
BottomUpPathCount = Other.BottomUpPathCount;
}
/// The top-down traversal uses this to merge information about predecessors to
/// form the initial state for a new block.
void BBState::MergePred(const BBState &Other) {
if (TopDownPathCount == OverflowOccurredValue)
return;
// Other.TopDownPathCount can be 0, in which case it is either dead or a
// loop backedge. Loop backedges are special.
TopDownPathCount += Other.TopDownPathCount;
// In order to be consistent, we clear the top down pointers when by adding
// TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
// has not occurred.
if (TopDownPathCount == OverflowOccurredValue) {
clearTopDownPointers();
return;
}
// Check for overflow. If we have overflow, fall back to conservative
// behavior.
if (TopDownPathCount < Other.TopDownPathCount) {
TopDownPathCount = OverflowOccurredValue;
clearTopDownPointers();
return;
}
// For each entry in the other set, if our set has an entry with the same key,
// merge the entries. Otherwise, copy the entry and merge it with an empty
// entry.
for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
MI != ME; ++MI) {
auto Pair = PerPtrTopDown.insert(*MI);
Pair.first->second.Merge(Pair.second ? TopDownPtrState() : MI->second,
/*TopDown=*/true);
}
// For each entry in our set, if the other set doesn't have an entry with the
// same key, force it to merge with an empty entry.
for (auto MI = top_down_ptr_begin(), ME = top_down_ptr_end(); MI != ME; ++MI)
if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
MI->second.Merge(TopDownPtrState(), /*TopDown=*/true);
}
/// The bottom-up traversal uses this to merge information about successors to
/// form the initial state for a new block.
void BBState::MergeSucc(const BBState &Other) {
if (BottomUpPathCount == OverflowOccurredValue)
return;
// Other.BottomUpPathCount can be 0, in which case it is either dead or a
// loop backedge. Loop backedges are special.
BottomUpPathCount += Other.BottomUpPathCount;
// In order to be consistent, we clear the top down pointers when by adding
// BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
// has not occurred.
if (BottomUpPathCount == OverflowOccurredValue) {
clearBottomUpPointers();
return;
}
// Check for overflow. If we have overflow, fall back to conservative
// behavior.
if (BottomUpPathCount < Other.BottomUpPathCount) {
BottomUpPathCount = OverflowOccurredValue;
clearBottomUpPointers();
return;
}
// For each entry in the other set, if our set has an entry with the
// same key, merge the entries. Otherwise, copy the entry and merge
// it with an empty entry.
for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
MI != ME; ++MI) {
auto Pair = PerPtrBottomUp.insert(*MI);
Pair.first->second.Merge(Pair.second ? BottomUpPtrState() : MI->second,
/*TopDown=*/false);
}
// For each entry in our set, if the other set doesn't have an entry
// with the same key, force it to merge with an empty entry.
for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME;
++MI)
if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
MI->second.Merge(BottomUpPtrState(), /*TopDown=*/false);
}
raw_ostream &llvm::operator<<(raw_ostream &OS, BBState &BBInfo) {
// Dump the pointers we are tracking.
OS << " TopDown State:\n";
if (!BBInfo.hasTopDownPtrs()) {
LLVM_DEBUG(dbgs() << " NONE!\n");
} else {
for (auto I = BBInfo.top_down_ptr_begin(), E = BBInfo.top_down_ptr_end();
I != E; ++I) {
const PtrState &P = I->second;
OS << " Ptr: " << *I->first
<< "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false")
<< "\n ImpreciseRelease: "
<< (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
<< " HasCFGHazards: "
<< (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
<< " KnownPositive: "
<< (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
<< " Seq: "
<< P.GetSeq() << "\n";
}
}
OS << " BottomUp State:\n";
if (!BBInfo.hasBottomUpPtrs()) {
LLVM_DEBUG(dbgs() << " NONE!\n");
} else {
for (auto I = BBInfo.bottom_up_ptr_begin(), E = BBInfo.bottom_up_ptr_end();
I != E; ++I) {
const PtrState &P = I->second;
OS << " Ptr: " << *I->first
<< "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false")
<< "\n ImpreciseRelease: "
<< (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
<< " HasCFGHazards: "
<< (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
<< " KnownPositive: "
<< (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
<< " Seq: "
<< P.GetSeq() << "\n";
}
}
return OS;
}
namespace {
/// The main ARC optimization pass.
class ObjCARCOpt {
bool Changed;
bool CFGChanged;
ProvenanceAnalysis PA;
/// A cache of references to runtime entry point constants.
ARCRuntimeEntryPoints EP;
/// A cache of MDKinds that can be passed into other functions to propagate
/// MDKind identifiers.
ARCMDKindCache MDKindCache;
BundledRetainClaimRVs *BundledInsts = nullptr;
/// A flag indicating whether the optimization that removes or moves
/// retain/release pairs should be performed.
bool DisableRetainReleasePairing = false;
/// Flags which determine whether each of the interesting runtime functions
/// is in fact used in the current function.
unsigned UsedInThisFunction;
bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
ARCInstKind &Class);
void OptimizeIndividualCalls(Function &F);
/// Optimize an individual call, optionally passing the
/// GetArgRCIdentityRoot if it has already been computed.
void OptimizeIndividualCallImpl(
Function &F, DenseMap<BasicBlock *, ColorVector> &BlockColors,
Instruction *Inst, ARCInstKind Class, const Value *Arg);
/// Try to optimize an AutoreleaseRV with a RetainRV or UnsafeClaimRV. If the
/// optimization occurs, returns true to indicate that the caller should
/// assume the instructions are dead.
bool OptimizeInlinedAutoreleaseRVCall(
Function &F, DenseMap<BasicBlock *, ColorVector> &BlockColors,
Instruction *Inst, const Value *&Arg, ARCInstKind Class,
Instruction *AutoreleaseRV, const Value *&AutoreleaseRVArg);
void CheckForCFGHazards(const BasicBlock *BB,
DenseMap<const BasicBlock *, BBState> &BBStates,
BBState &MyStates) const;
bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
BlotMapVector<Value *, RRInfo> &Retains,
BBState &MyStates);
bool VisitBottomUp(BasicBlock *BB,
DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains);
bool VisitInstructionTopDown(
Instruction *Inst, DenseMap<Value *, RRInfo> &Releases, BBState &MyStates,
const DenseMap<const Instruction *, SmallPtrSet<const Value *, 2>>
&ReleaseInsertPtToRCIdentityRoots);
bool VisitTopDown(
BasicBlock *BB, DenseMap<const BasicBlock *, BBState> &BBStates,
DenseMap<Value *, RRInfo> &Releases,
const DenseMap<const Instruction *, SmallPtrSet<const Value *, 2>>
&ReleaseInsertPtToRCIdentityRoots);
bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases);
void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases,
SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
bool PairUpRetainsAndReleases(DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases, Module *M,
Instruction *Retain,
SmallVectorImpl<Instruction *> &DeadInsts,
RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
Value *Arg, bool KnownSafe,
bool &AnyPairsCompletelyEliminated);
bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
BlotMapVector<Value *, RRInfo> &Retains,
DenseMap<Value *, RRInfo> &Releases, Module *M);
void OptimizeWeakCalls(Function &F);
bool OptimizeSequences(Function &F);
void OptimizeReturns(Function &F);
#ifndef NDEBUG
void GatherStatistics(Function &F, bool AfterOptimization = false);
#endif
public:
void init(Module &M);
bool run(Function &F, AAResults &AA);
bool hasCFGChanged() const { return CFGChanged; }
};
} // end anonymous namespace
/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
/// not a return value.
bool
ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
// Check for the argument being from an immediately preceding call or invoke.
const Value *Arg = GetArgRCIdentityRoot(RetainRV);
if (const Instruction *Call = dyn_cast<CallBase>(Arg)) {
if (Call->getParent() == RetainRV->getParent()) {
BasicBlock::const_iterator I(Call);
++I;
while (IsNoopInstruction(&*I))
++I;
if (&*I == RetainRV)
return false;
} else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
BasicBlock *RetainRVParent = RetainRV->getParent();
if (II->getNormalDest() == RetainRVParent) {
BasicBlock::const_iterator I = RetainRVParent->begin();
while (IsNoopInstruction(&*I))
++I;
if (&*I == RetainRV)
return false;
}
}
}
assert(!BundledInsts->contains(RetainRV) &&
"a bundled retainRV's argument should be a call");
// Turn it to a plain objc_retain.
Changed = true;
++NumPeeps;
LLVM_DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
"objc_retain since the operand is not a return value.\n"
"Old = "
<< *RetainRV << "\n");
Function *NewDecl = EP.get(ARCRuntimeEntryPointKind::Retain);
cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
LLVM_DEBUG(dbgs() << "New = " << *RetainRV << "\n");
return false;
}
bool ObjCARCOpt::OptimizeInlinedAutoreleaseRVCall(
Function &F, DenseMap<BasicBlock *, ColorVector> &BlockColors,
Instruction *Inst, const Value *&Arg, ARCInstKind Class,
Instruction *AutoreleaseRV, const Value *&AutoreleaseRVArg) {
if (BundledInsts->contains(Inst))
return false;
// Must be in the same basic block.
assert(Inst->getParent() == AutoreleaseRV->getParent());
// Must operate on the same root.
Arg = GetArgRCIdentityRoot(Inst);
AutoreleaseRVArg = GetArgRCIdentityRoot(AutoreleaseRV);
if (Arg != AutoreleaseRVArg) {
// If there isn't an exact match, check if we have equivalent PHIs.
const PHINode *PN = dyn_cast<PHINode>(Arg);
if (!PN)
return false;
SmallVector<const Value *, 4> ArgUsers;
getEquivalentPHIs(*PN, ArgUsers);
if (!llvm::is_contained(ArgUsers, AutoreleaseRVArg))
return false;
}
// Okay, this is a match. Merge them.
++NumPeeps;
LLVM_DEBUG(dbgs() << "Found inlined objc_autoreleaseReturnValue '"
<< *AutoreleaseRV << "' paired with '" << *Inst << "'\n");
// Delete the RV pair, starting with the AutoreleaseRV.
AutoreleaseRV->replaceAllUsesWith(
cast<CallInst>(AutoreleaseRV)->getArgOperand(0));
Changed = true;
EraseInstruction(AutoreleaseRV);
if (Class == ARCInstKind::RetainRV) {
// AutoreleaseRV and RetainRV cancel out. Delete the RetainRV.
Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
EraseInstruction(Inst);
return true;
}
// UnsafeClaimRV is a frontend peephole for RetainRV + Release. Since the
// AutoreleaseRV and RetainRV cancel out, replace UnsafeClaimRV with Release.
assert(Class == ARCInstKind::UnsafeClaimRV);
Value *CallArg = cast<CallInst>(Inst)->getArgOperand(0);
CallInst *Release = CallInst::Create(
EP.get(ARCRuntimeEntryPointKind::Release), CallArg, "", Inst);
assert(IsAlwaysTail(ARCInstKind::UnsafeClaimRV) &&
"Expected UnsafeClaimRV to be safe to tail call");
Release->setTailCall();
Inst->replaceAllUsesWith(CallArg);
EraseInstruction(Inst);
// Run the normal optimizations on Release.
OptimizeIndividualCallImpl(F, BlockColors, Release, ARCInstKind::Release,
Arg);
return true;
}
/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
/// used as a return value.
void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
Instruction *AutoreleaseRV,
ARCInstKind &Class) {
// Check for a return of the pointer value.
const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
// If the argument is ConstantPointerNull or UndefValue, its other users
// aren't actually interesting to look at.
if (isa<ConstantData>(Ptr))
return;
SmallVector<const Value *, 2> Users;
Users.push_back(Ptr);
// Add PHIs that are equivalent to Ptr to Users.
if (const PHINode *PN = dyn_cast<PHINode>(Ptr))
getEquivalentPHIs(*PN, Users);
do {
Ptr = Users.pop_back_val();
for (const User *U : Ptr->users()) {
if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
return;
if (isa<BitCastInst>(U))
Users.push_back(U);
}
} while (!Users.empty());
Changed = true;
++NumPeeps;
LLVM_DEBUG(
dbgs() << "Transforming objc_autoreleaseReturnValue => "
"objc_autorelease since its operand is not used as a return "
"value.\n"
"Old = "
<< *AutoreleaseRV << "\n");
CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
Function *NewDecl = EP.get(ARCRuntimeEntryPointKind::Autorelease);
AutoreleaseRVCI->setCalledFunction(NewDecl);
AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Class = ARCInstKind::Autorelease;
LLVM_DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
}
namespace {
Instruction *
CloneCallInstForBB(CallInst &CI, BasicBlock &BB,
const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
SmallVector<OperandBundleDef, 1> OpBundles;
for (unsigned I = 0, E = CI.getNumOperandBundles(); I != E; ++I) {
auto Bundle = CI.getOperandBundleAt(I);
// Funclets will be reassociated in the future.
if (Bundle.getTagID() == LLVMContext::OB_funclet)
continue;
OpBundles.emplace_back(Bundle);
}
if (!BlockColors.empty()) {
const ColorVector &CV = BlockColors.find(&BB)->second;
assert(CV.size() == 1 && "non-unique color for block!");
Instruction *EHPad = CV.front()->getFirstNonPHI();
if (EHPad->isEHPad())
OpBundles.emplace_back("funclet", EHPad);
}
return CallInst::Create(&CI, OpBundles);
}
}
/// Visit each call, one at a time, and make simplifications without doing any
/// additional analysis.
void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
// Reset all the flags in preparation for recomputing them.
UsedInThisFunction = 0;
DenseMap<BasicBlock *, ColorVector> BlockColors;
if (F.hasPersonalityFn() &&
isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
BlockColors = colorEHFunclets(F);
// Store any delayed AutoreleaseRV intrinsics, so they can be easily paired
// with RetainRV and UnsafeClaimRV.
Instruction *DelayedAutoreleaseRV = nullptr;
const Value *DelayedAutoreleaseRVArg = nullptr;
auto setDelayedAutoreleaseRV = [&](Instruction *AutoreleaseRV) {
assert(!DelayedAutoreleaseRV || !AutoreleaseRV);
DelayedAutoreleaseRV = AutoreleaseRV;
DelayedAutoreleaseRVArg = nullptr;
};
auto optimizeDelayedAutoreleaseRV = [&]() {
if (!DelayedAutoreleaseRV)
return;
OptimizeIndividualCallImpl(F, BlockColors, DelayedAutoreleaseRV,
ARCInstKind::AutoreleaseRV,
DelayedAutoreleaseRVArg);
setDelayedAutoreleaseRV(nullptr);
};
auto shouldDelayAutoreleaseRV = [&](Instruction *NonARCInst) {
// Nothing to delay, but we may as well skip the logic below.
if (!DelayedAutoreleaseRV)
return true;
// If we hit the end of the basic block we're not going to find an RV-pair.
// Stop delaying.
if (NonARCInst->isTerminator())
return false;
// Given the frontend rules for emitting AutoreleaseRV, RetainRV, and
// UnsafeClaimRV, it's probably safe to skip over even opaque function calls
// here since OptimizeInlinedAutoreleaseRVCall will confirm that they
// have the same RCIdentityRoot. However, what really matters is
// skipping instructions or intrinsics that the inliner could leave behind;
// be conservative for now and don't skip over opaque calls, which could
// potentially include other ARC calls.
auto *CB = dyn_cast<CallBase>(NonARCInst);
if (!CB)
return true;
return CB->getIntrinsicID() != Intrinsic::not_intrinsic;
};
// Visit all objc_* calls in F.
for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
Instruction *Inst = &*I++;
if (auto *CI = dyn_cast<CallInst>(Inst))
if (objcarc::hasAttachedCallOpBundle(CI)) {
BundledInsts->insertRVCall(&*I, CI);
Changed = true;
}
ARCInstKind Class = GetBasicARCInstKind(Inst);
// Skip this loop if this instruction isn't itself an ARC intrinsic.
const Value *Arg = nullptr;
switch (Class) {
default:
optimizeDelayedAutoreleaseRV();
break;
case ARCInstKind::CallOrUser:
case ARCInstKind::User:
case ARCInstKind::None:
// This is a non-ARC instruction. If we're delaying an AutoreleaseRV,
// check if it's safe to skip over it; if not, optimize the AutoreleaseRV
// now.
if (!shouldDelayAutoreleaseRV(Inst))
optimizeDelayedAutoreleaseRV();
continue;
case ARCInstKind::AutoreleaseRV:
optimizeDelayedAutoreleaseRV();
setDelayedAutoreleaseRV(Inst);
continue;
case ARCInstKind::RetainRV:
case ARCInstKind::UnsafeClaimRV:
if (DelayedAutoreleaseRV) {
// We have a potential RV pair. Check if they cancel out.
if (OptimizeInlinedAutoreleaseRVCall(F, BlockColors, Inst, Arg, Class,
DelayedAutoreleaseRV,
DelayedAutoreleaseRVArg)) {
setDelayedAutoreleaseRV(nullptr);
continue;
}
optimizeDelayedAutoreleaseRV();
}
break;
}
OptimizeIndividualCallImpl(F, BlockColors, Inst, Class, Arg);
}
// Catch the final delayed AutoreleaseRV.
optimizeDelayedAutoreleaseRV();
}
/// This function returns true if the value is inert. An ObjC ARC runtime call
/// taking an inert operand can be safely deleted.
static bool isInertARCValue(Value *V, SmallPtrSet<Value *, 1> &VisitedPhis) {
V = V->stripPointerCasts();
if (IsNullOrUndef(V))
return true;
// See if this is a global attribute annotated with an 'objc_arc_inert'.
if (auto *GV = dyn_cast<GlobalVariable>(V))
if (GV->hasAttribute("objc_arc_inert"))
return true;
if (auto PN = dyn_cast<PHINode>(V)) {
// Ignore this phi if it has already been discovered.
if (!VisitedPhis.insert(PN).second)
return true;
// Look through phis's operands.
for (Value *Opnd : PN->incoming_values())
if (!isInertARCValue(Opnd, VisitedPhis))
return false;
return true;
}
return false;
}
void ObjCARCOpt::OptimizeIndividualCallImpl(
Function &F, DenseMap<BasicBlock *, ColorVector> &BlockColors,
Instruction *Inst, ARCInstKind Class, const Value *Arg) {
LLVM_DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
// We can delete this call if it takes an inert value.
SmallPtrSet<Value *, 1> VisitedPhis;
if (BundledInsts->contains(Inst)) {
UsedInThisFunction |= 1 << unsigned(Class);
return;
}
if (IsNoopOnGlobal(Class))
if (isInertARCValue(Inst->getOperand(0), VisitedPhis)) {
if (!Inst->getType()->isVoidTy())
Inst->replaceAllUsesWith(Inst->getOperand(0));
Inst->eraseFromParent();
Changed = true;
return;
}
switch (Class) {
default:
break;
// Delete no-op casts. These function calls have special semantics, but
// the semantics are entirely implemented via lowering in the front-end,
// so by the time they reach the optimizer, they are just no-op calls
// which return their argument.
//
// There are gray areas here, as the ability to cast reference-counted
// pointers to raw void* and back allows code to break ARC assumptions,
// however these are currently considered to be unimportant.
case ARCInstKind::NoopCast:
Changed = true;
++NumNoops;
LLVM_DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
EraseInstruction(Inst);
return;
// If the pointer-to-weak-pointer is null, it's undefined behavior.
case ARCInstKind::StoreWeak:
case ARCInstKind::LoadWeak:
case ARCInstKind::LoadWeakRetained:
case ARCInstKind::InitWeak:
case ARCInstKind::DestroyWeak: {
CallInst *CI = cast<CallInst>(Inst);
if (IsNullOrUndef(CI->getArgOperand(0))) {
Changed = true;
new StoreInst(ConstantInt::getTrue(CI->getContext()),
UndefValue::get(Type::getInt1PtrTy(CI->getContext())), CI);
Value *NewValue = UndefValue::get(CI->getType());
LLVM_DEBUG(
dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
"\nOld = "
<< *CI << "\nNew = " << *NewValue << "\n");
CI->replaceAllUsesWith(NewValue);
CI->eraseFromParent();
return;
}
break;
}
case ARCInstKind::CopyWeak:
case ARCInstKind::MoveWeak: {
CallInst *CI = cast<CallInst>(Inst);
if (IsNullOrUndef(CI->getArgOperand(0)) ||
IsNullOrUndef(CI->getArgOperand(1))) {
Changed = true;
new StoreInst(ConstantInt::getTrue(CI->getContext()),
UndefValue::get(Type::getInt1PtrTy(CI->getContext())), CI);
Value *NewValue = UndefValue::get(CI->getType());
LLVM_DEBUG(
dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
"\nOld = "
<< *CI << "\nNew = " << *NewValue << "\n");
CI->replaceAllUsesWith(NewValue);
CI->eraseFromParent();
return;
}
break;
}
case ARCInstKind::RetainRV:
if (OptimizeRetainRVCall(F, Inst))
return;
break;
case ARCInstKind::AutoreleaseRV:
OptimizeAutoreleaseRVCall(F, Inst, Class);
break;
}
// objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
if (IsAutorelease(Class) && Inst->use_empty()) {
CallInst *Call = cast<CallInst>(Inst);
const Value *Arg = Call->getArgOperand(0);
Arg = FindSingleUseIdentifiedObject(Arg);
if (Arg) {
Changed = true;
++NumAutoreleases;
// Create the declaration lazily.
LLVMContext &C = Inst->getContext();
Function *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
CallInst *NewCall =
CallInst::Create(Decl, Call->getArgOperand(0), "", Call);