forked from facebook/redex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathControlFlow.cpp
3412 lines (3040 loc) · 109 KB
/
ControlFlow.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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ControlFlow.h"
#include <boost/dynamic_bitset.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <iterator>
#include <queue>
#include <stack>
#include <utility>
#include "CppUtil.h"
#include "DexInstruction.h"
#include "DexPosition.h"
#include "DexUtil.h"
#include "GraphUtil.h"
#include "IRList.h"
#include "InstructionLowering.h"
#include "RedexContext.h"
#include "Show.h"
#include "SourceBlocks.h"
#include "Trace.h"
#include "Transform.h"
std::atomic<size_t> build_cfg_counter{0};
namespace {
bool edge_type_structural_equals(std::vector<cfg::Edge*> e1,
std::vector<cfg::Edge*> e2) {
if (e1.empty() && e2.empty()) {
return true;
}
if (e1.empty() || e2.empty()) {
return false;
}
if (e1.size() != e2.size()) {
return false;
}
std::unordered_map<cfg::EdgeType, int> edge_types;
for (size_t i = 0; i < e1.size(); i++) {
edge_types[e1[i]->type()] += 1;
edge_types[e2[i]->type()] -= 1;
}
for (auto pair : edge_types) {
if (pair.second != 0) {
return false;
}
}
return true;
}
// return true if `it` should be the last instruction of this block
bool end_of_block(const IRList* ir, const IRList::iterator& it, bool in_try) {
auto next = std::next(it);
if (next == ir->end()) {
return true;
}
// End the block before the first target in a contiguous sequence of targets.
if (next->type == MFLOW_TARGET && it->type != MFLOW_TARGET) {
return true;
}
// End the block before the first catch marker in a contiguous sequence of
// catch markers.
if (next->type == MFLOW_CATCH && it->type != MFLOW_CATCH) {
return true;
}
// End the block before a TRY_START
// and after a TRY_END
if ((next->type == MFLOW_TRY && next->tentry->type == TRY_START) ||
(it->type == MFLOW_TRY && it->tentry->type == TRY_END)) {
return true;
}
if (in_try && it->type == MFLOW_OPCODE &&
opcode::may_throw(it->insn->opcode())) {
return true;
}
if (it->type != MFLOW_OPCODE) {
return false;
}
if (opcode::is_branch(it->insn->opcode()) ||
opcode::is_a_return(it->insn->opcode()) ||
it->insn->opcode() == OPCODE_THROW) {
return true;
}
return false;
}
bool ends_with_may_throw(cfg::Block* p) {
for (auto last = p->rbegin(); last != p->rend(); ++last) {
if (last->type != MFLOW_OPCODE) {
continue;
}
return opcode::can_throw(last->insn->opcode());
}
return false;
}
/*
* Given an method-item-entry ordering, delete positions that are...
* - duplicates with the previous position, even across block boundaries
* (they will get reconstituted when the cfg is rebuild)
* - adjacent to an immediately following position, as the last position wins.
* Parent positions are kept as needed.
*/
void remove_redundant_positions(IRList* ir) {
// We build a set of duplicate positions.
std::unordered_set<DexPosition*> duplicate_positions;
std::unordered_map<DexPosition*, IRList::iterator> positions_to_remove;
DexPosition* prev = nullptr;
for (auto it = ir->begin(); it != ir->end(); it++) {
if (it->type == MFLOW_POSITION) {
DexPosition* curr = it->pos.get();
positions_to_remove.emplace(curr, it);
if (prev != nullptr && *curr == *prev) {
duplicate_positions.insert(curr);
}
prev = curr;
}
}
// Backward pass to find positions that are not adjacent to an immediately
// following position and must be kept (including their parents).
bool keep_prev = false;
for (auto it = ir->rbegin(); it != ir->rend(); it++) {
switch (it->type) {
case MFLOW_OPCODE:
case MFLOW_DEX_OPCODE:
case MFLOW_TARGET:
case MFLOW_TRY:
case MFLOW_CATCH:
keep_prev = true;
break;
case MFLOW_POSITION: {
DexPosition* curr = it->pos.get();
if (keep_prev && !duplicate_positions.count(curr)) {
for (auto pos = curr; pos && positions_to_remove.erase(pos);
pos = pos->parent) {
}
keep_prev = false;
}
break;
}
case MFLOW_SOURCE_BLOCK:
case MFLOW_DEBUG:
case MFLOW_FALLTHROUGH:
// ignore
break;
}
}
// Final pass to do the actual deletion.
for (auto& p : positions_to_remove) {
ir->erase_and_dispose(p.second);
}
}
// Follow the catch entry linked list starting at `first_mie` and check if the
// throw edges (pointed to by `it`) are equivalent to the linked list. The throw
// edges should be sorted by their indices.
//
// This function is useful in avoiding generating multiple identical catch
// entries.
//
// Used while turning back into a linear representation.
bool catch_entries_equivalent_to_throw_edges(
cfg::ControlFlowGraph* cfg,
MethodItemEntry* first_mie,
std::vector<cfg::Edge*>::iterator it,
std::vector<cfg::Edge*>::iterator end,
const std::unordered_map<MethodItemEntry*, cfg::Block*>&
catch_to_containing_block) {
for (auto mie = first_mie; mie != nullptr; mie = mie->centry->next) {
always_assert(mie->type == MFLOW_CATCH);
if (it == end) {
return false;
}
auto edge = *it;
if (mie->centry->catch_type != edge->throw_info()->catch_type) {
return false;
}
const auto& search = catch_to_containing_block.find(mie);
always_assert_log(search != catch_to_containing_block.end(),
"%s not found in %s", SHOW(*mie), SHOW(*cfg));
if (search->second != edge->target()) {
return false;
}
++it;
}
return it == end;
}
} // namespace
namespace cfg {
namespace details {
std::string show_cfg(const ControlFlowGraph& cfg) { return show(cfg); }
std::string show_insn(const IRInstruction* insn) { return show(insn); }
} // namespace details
void Block::free() {
for (auto& mie : *this) {
switch (mie.type) {
case MFLOW_OPCODE:
delete mie.insn;
mie.insn = nullptr;
break;
case MFLOW_DEX_OPCODE:
delete mie.dex_insn;
mie.dex_insn = nullptr;
break;
default:
break;
}
}
}
void Block::cleanup_debug(std::unordered_set<reg_t>& valid_regs) {
this->m_entries.cleanup_debug(valid_regs);
}
IRList::iterator Block::begin() {
if (m_parent->editable()) {
return m_entries.begin();
} else {
return m_begin;
}
}
IRList::iterator Block::end() {
if (m_parent->editable()) {
return m_entries.end();
} else {
return m_end;
}
}
IRList::const_iterator Block::begin() const {
if (m_parent->editable()) {
return m_entries.begin();
} else {
return m_begin;
}
}
IRList::const_iterator Block::end() const {
if (m_parent->editable()) {
return m_entries.end();
} else {
return m_end;
}
}
bool Block::is_catch() const {
return m_parent->get_pred_edge_of_type(this, EDGE_THROW) != nullptr;
}
bool Block::same_try(const Block* other) const {
always_assert(other->m_parent == this->m_parent);
return m_parent->blocks_are_in_same_try(this, other);
}
void Block::remove_insn(const InstructionIterator& it) {
always_assert(m_parent->editable());
m_parent->remove_insn(it);
}
void Block::remove_insn(const ir_list::InstructionIterator& it) {
always_assert(m_parent->editable());
remove_insn(to_cfg_instruction_iterator(it));
}
void Block::remove_insn(const IRList::iterator& it) {
always_assert(m_parent->editable());
remove_insn(to_cfg_instruction_iterator(it));
}
IRList::iterator Block::remove_mie(const IRList::iterator& it) {
if (it->type == MFLOW_OPCODE) {
m_parent->m_removed_insns.push_back(it->insn);
}
return m_entries.erase_and_dispose(it);
}
opcode::Branchingness Block::branchingness() const {
// TODO (cnli): put back 'always_assert(m_parent->editable());'
// once ModelMethodMerger::sink_common_ctor_to_return_block update
// to editable CFG.
const auto& last = get_last_insn();
if (succs().empty() ||
(succs().size() == 1 &&
m_parent->get_succ_edge_of_type(this, EDGE_GHOST) != nullptr)) {
if (last != end()) {
auto op = last->insn->opcode();
if (opcode::is_a_return(op)) {
return opcode::BRANCH_RETURN;
} else if (op == OPCODE_THROW) {
return opcode::BRANCH_THROW;
}
}
return opcode::BRANCH_NONE;
}
if (m_parent->get_succ_edge_of_type(this, EDGE_THROW) != nullptr) {
return opcode::BRANCH_THROW;
}
if (m_parent->get_succ_edge_of_type(this, EDGE_BRANCH) != nullptr) {
always_assert(last != end());
auto br = opcode::branchingness(last->insn->opcode());
always_assert(br == opcode::BRANCH_IF || br == opcode::BRANCH_SWITCH);
return br;
}
if (m_parent->get_succ_edge_of_type(this, EDGE_GOTO) != nullptr) {
return opcode::BRANCH_GOTO;
}
return opcode::BRANCH_NONE;
}
uint32_t Block::num_opcodes() const {
always_assert(m_parent->editable());
return m_entries.count_opcodes();
}
uint32_t Block::sum_opcode_sizes() const {
always_assert(m_parent->editable());
return m_entries.sum_opcode_sizes();
}
uint32_t Block::estimate_code_units() const {
always_assert(m_parent->editable());
auto code_units = m_entries.estimate_code_units();
auto it = get_last_insn();
if (it != end() && opcode::is_switch(it->insn->opcode())) {
instruction_lowering::CaseKeysExtentBuilder case_keys;
for (auto* e : succs()) {
if (e->type() == EDGE_BRANCH) {
case_keys.insert(*e->case_key());
}
}
code_units += case_keys->estimate_switch_payload_code_units();
}
return code_units;
}
bool Block::is_unreachable() const {
std::unordered_set<const cfg::Block*> visited;
for (auto* block = this; block && visited.insert(block).second;) {
auto ii = ir_list::ConstInstructionIterable(block);
for (auto it = ii.begin(); it != ii.end(); ++it) {
if (opcode::is_unreachable(it->insn->opcode())) {
return true;
}
if (opcode::is_a_load_param(it->insn->opcode())) {
continue;
}
return false;
}
block = block->goes_to_only_edge();
}
// We hit a non-terminating loop; that doesn't make this this unreachable.
return false;
}
// shallowly copy pointers (edges and parent cfg)
// but deeply copy MethodItemEntries
Block::Block(const Block& b, MethodItemEntryCloner* cloner)
: m_id(b.m_id),
m_preds(b.m_preds),
m_succs(b.m_succs),
m_parent(b.m_parent) {
// only for editable, don't worry about m_begin and m_end
always_assert(m_parent->editable());
for (const auto& mie : b.m_entries) {
m_entries.push_back(*cloner->clone(&mie));
}
}
bool Block::has_pred(Block* b, EdgeType t) const {
const auto& edges = preds();
return std::find_if(edges.begin(), edges.end(), [b, t](const Edge* edge) {
return edge->src() == b &&
(t == EDGE_TYPE_SIZE || edge->type() == t);
}) != edges.end();
}
bool Block::has_succ(Block* b, EdgeType t) const {
const auto& edges = succs();
return std::find_if(edges.begin(), edges.end(), [b, t](const Edge* edge) {
return edge->target() == b &&
(t == EDGE_TYPE_SIZE || edge->type() == t);
}) != edges.end();
}
IRList::iterator Block::get_conditional_branch() {
for (auto it = rbegin(); it != rend(); ++it) {
if (it->type == MFLOW_OPCODE) {
auto op = it->insn->opcode();
if (opcode::is_a_conditional_branch(op) || opcode::is_switch(op)) {
return std::prev(it.base());
}
}
}
return end();
}
IRList::iterator Block::get_last_insn() {
for (auto it = rbegin(); it != rend(); ++it) {
if (it->type == MFLOW_OPCODE) {
// Reverse iterators have a member base() which returns a corresponding
// forward iterator. Beware that this isn't an iterator that refers to the
// same object - it actually refers to the next object in the sequence.
// This is so that rbegin() corresponds with end() and rend() corresponds
// with begin(). Copied from https://stackoverflow.com/a/2037917
return std::prev(it.base());
}
}
return end();
}
IRList::const_iterator Block::get_last_insn() const {
for (auto it = rbegin(); it != rend(); ++it) {
if (it->type == MFLOW_OPCODE) {
// Reverse iterators have a member base() which returns a corresponding
// forward iterator. Beware that this isn't an iterator that refers to the
// same object - it actually refers to the next object in the sequence.
// This is so that rbegin() corresponds with end() and rend() corresponds
// with begin(). Copied from https://stackoverflow.com/a/2037917
return std::prev(it.base());
}
}
return end();
}
IRList::iterator Block::get_first_insn() {
for (auto it = begin(); it != end(); ++it) {
if (it->type == MFLOW_OPCODE) {
return it;
}
}
return end();
}
IRList::const_iterator Block::get_first_insn() const {
for (auto it = begin(); it != end(); ++it) {
if (it->type == MFLOW_OPCODE) {
return it;
}
}
return end();
}
IRList::iterator Block::get_first_non_param_loading_insn() {
for (auto it = begin(); it != end(); ++it) {
if (it->type != MFLOW_OPCODE) {
continue;
}
if (!opcode::is_a_load_param(it->insn->opcode())) {
return it;
}
}
return end();
}
IRList::const_iterator Block::get_first_non_param_loading_insn() const {
for (auto it = begin(); it != end(); ++it) {
if (it->type != MFLOW_OPCODE) {
continue;
}
if (!opcode::is_a_load_param(it->insn->opcode())) {
return it;
}
}
return end();
}
IRList::iterator Block::get_last_param_loading_insn() {
IRList::iterator res = end();
for (auto it = begin(); it != end(); ++it) {
if (it->type != MFLOW_OPCODE) {
continue;
}
if (opcode::is_a_load_param(it->insn->opcode())) {
res = it;
} else {
// There won't be another one.
break;
}
}
return res;
}
IRList::const_iterator Block::get_last_param_loading_insn() const {
IRList::const_iterator res = end();
for (auto it = begin(); it != end(); ++it) {
if (it->type != MFLOW_OPCODE) {
continue;
}
if (opcode::is_a_load_param(it->insn->opcode())) {
res = it;
} else {
// There won't be another one.
break;
}
}
return res;
}
IRList::iterator Block::get_first_insn_before_position() {
for (auto it = begin(); it != end(); ++it) {
if (it->type == MFLOW_OPCODE) {
auto op = it->insn->opcode();
if (!opcode::is_move_result_any(op) && !opcode::is_goto(op)) {
return it;
}
} else if (it->type == MFLOW_POSITION) {
return end();
}
}
return end();
}
IRList::const_iterator Block::get_first_insn_before_position() const {
for (auto it = begin(); it != end(); ++it) {
if (it->type == MFLOW_OPCODE) {
auto op = it->insn->opcode();
if (!opcode::is_move_result_any(op) && !opcode::is_goto(op)) {
return it;
}
} else if (it->type == MFLOW_POSITION) {
return end();
}
}
return end();
}
bool Block::starts_with_move_result() const {
auto first_it = get_first_insn();
if (first_it != end()) {
auto first_op = first_it->insn->opcode();
if (opcode::is_move_result_any(first_op)) {
return true;
}
}
return false;
}
bool Block::starts_with_move_exception() const {
auto first_it = get_first_insn();
if (first_it != end()) {
auto first_op = first_it->insn->opcode();
if (opcode::is_move_exception(first_op)) {
return true;
}
}
return false;
}
bool Block::contains_opcode(IROpcode opcode) const {
for (auto it = begin(); it != end(); ++it) {
if (it->type != MFLOW_OPCODE) {
continue;
}
if (it->insn->opcode() == opcode) {
return true;
}
}
return false;
}
bool Block::begins_with(Block* other) const {
IRList::const_iterator self_it = this->begin();
IRList::const_iterator other_it = other->begin();
while (self_it != this->end() && other_it != other->end()) {
if (*self_it != *other_it) {
return false;
}
self_it++;
other_it++;
}
return other_it == other->end();
}
Block* Block::goes_to() const {
const Edge* e = m_parent->get_succ_edge_of_type(this, EDGE_GOTO);
if (e != nullptr) {
return e->target();
}
return nullptr;
}
Block* Block::goes_to_only_edge() const {
const auto& s = succs();
if (s.size() == 1) {
const auto& e = s[0];
if (e->type() == EDGE_GOTO) {
return e->target();
}
}
return nullptr;
}
bool Block::cannot_throw() const {
for (auto& mie : ir_list::ConstInstructionIterable(this)) {
if (opcode::can_throw(mie.insn->opcode())) {
return false;
}
}
return true;
}
std::vector<Edge*> Block::get_outgoing_throws_in_order() const {
std::vector<Edge*> result =
m_parent->get_succ_edges_of_type(this, EDGE_THROW);
std::sort(result.begin(), result.end(), [](const Edge* e1, const Edge* e2) {
return e1->throw_info()->index < e2->throw_info()->index;
});
return result;
}
std::vector<Edge*> Block::get_outgoing_branches_in_order() const {
std::vector<Edge*> result =
m_parent->get_succ_edges_of_type(this, EDGE_BRANCH);
if (result.size() > 1) {
std::sort(result.begin(), result.end(), [](const Edge* e1, const Edge* e2) {
return e1->case_key() < e2->case_key();
});
}
return result;
}
// These assume that the iterator is inside this block
cfg::InstructionIterator Block::to_cfg_instruction_iterator(
const ir_list::InstructionIterator& list_it, bool next_on_end) {
if (ControlFlowGraph::DEBUG && list_it.unwrap() != end()) {
bool inside = false;
auto needle = list_it.unwrap();
for (auto it = begin(); it != end(); ++it) {
if (it == needle) {
inside = true;
}
}
always_assert(inside);
}
auto it = cfg::InstructionIterator(*m_parent, this, list_it);
if (next_on_end && list_it.unwrap() == end()) {
++it;
}
return it;
}
cfg::InstructionIterator Block::to_cfg_instruction_iterator(
const IRList::iterator& list_it, bool next_on_end) {
always_assert(list_it == this->end() || list_it->type == MFLOW_OPCODE);
return to_cfg_instruction_iterator(
ir_list::InstructionIterator(list_it, this->end()), next_on_end);
}
cfg::InstructionIterator Block::to_cfg_instruction_iterator(
MethodItemEntry& mie) {
always_assert(m_parent->editable());
return to_cfg_instruction_iterator(m_entries.iterator_to(mie));
}
// Forward the insertion methods to the parent CFG.
bool Block::insert_before(const InstructionIterator& position,
const std::vector<IRInstruction*>& insns) {
always_assert(position.block() == this);
return m_parent->insert_before(position, insns);
}
bool Block::insert_before(const InstructionIterator& position,
IRInstruction* insn) {
always_assert(position.block() == this);
return m_parent->insert_before(position, insn);
}
bool Block::insert_after(const InstructionIterator& position,
const std::vector<IRInstruction*>& insns) {
always_assert(position.block() == this);
return m_parent->insert_after(position, insns);
}
bool Block::insert_after(const InstructionIterator& position,
IRInstruction* insn) {
always_assert(position.block() == this);
return m_parent->insert_after(position, insn);
}
bool Block::push_front(const std::vector<IRInstruction*>& insns) {
return m_parent->push_front(this, insns);
}
bool Block::push_front(IRInstruction* insn) {
return m_parent->push_front(this, insn);
}
bool Block::push_back(const std::vector<IRInstruction*>& insns) {
return m_parent->push_back(this, insns);
}
bool Block::push_back(IRInstruction* insn) {
return m_parent->push_back(this, insn);
}
bool Block::structural_equals(const Block* other) const {
return this->structural_equals(other, std::equal_to<const IRInstruction&>());
}
bool Block::structural_equals(
const Block* other, const InstructionEquality& instruction_equals) const {
auto iterable1 = ir_list::ConstInstructionIterable(this);
auto iterable2 = ir_list::ConstInstructionIterable(other);
auto it1 = iterable1.begin();
auto it2 = iterable2.begin();
for (; it1 != iterable1.end() && it2 != iterable2.end(); ++it1, ++it2) {
auto& mie1 = *it1;
auto& mie2 = *it2;
if (!instruction_equals(*mie1.insn, *mie2.insn)) {
return false;
}
}
return it1 == iterable1.end() && it2 == iterable2.end();
}
bool Block::extended_structural_equals(
const Block* other, const InstructionEquality& instruction_equals) const {
if (!edge_type_structural_equals(this->preds(), other->preds()) ||
!edge_type_structural_equals(this->succs(), other->succs())) {
return false;
}
return this->structural_equals(other, instruction_equals);
}
std::ostream& operator<<(std::ostream& os, const Edge& e) {
switch (e.type()) {
case EDGE_GOTO:
return os << "goto";
case EDGE_BRANCH: {
os << "branch";
const auto& key = e.case_key();
if (key) {
os << " " << *key;
}
return os;
}
case EDGE_THROW:
return os << "throw";
case EDGE_GHOST:
return os << "ghost";
case EDGE_TYPE_SIZE:
break;
}
not_reached();
}
bool ControlFlowGraph::DEBUG = false;
ControlFlowGraph::ControlFlowGraph(IRList* ir,
reg_t registers_size,
bool editable)
: m_orig_list(editable ? nullptr : ir),
m_registers_size(registers_size),
m_editable(editable) {
always_assert_log(!ir->empty(), "IRList contains no instructions");
build_cfg_counter++;
BranchToTargets branch_to_targets;
TryEnds try_ends;
TryCatches try_catches;
find_block_boundaries(ir, branch_to_targets, try_ends, try_catches);
connect_blocks(branch_to_targets);
add_catch_edges(try_ends, try_catches);
if (m_editable) {
remove_try_catch_markers();
// Often, the `registers_size` parameter passed into this constructor is
// incorrect. We recompute here to safeguard against this.
// TODO: fix the optimizations that don't track registers size correctly.
recompute_registers_size();
TRACE_NO_LINE(CFG, 5, "before simplify:\n%s", SHOW(*this));
simplify();
TRACE_NO_LINE(CFG, 5, "after simplify:\n%s", SHOW(*this));
} else {
remove_unreachable_succ_edges();
}
TRACE_NO_LINE(CFG, 5, "editable %d, %s", m_editable, SHOW(*this));
}
void ControlFlowGraph::find_block_boundaries(IRList* ir,
BranchToTargets& branch_to_targets,
TryEnds& try_ends,
TryCatches& try_catches) {
// create the entry block
auto* block = create_block();
IRList::iterator block_begin;
if (m_editable) {
block_begin = ir->begin();
} else {
block->m_begin = ir->begin();
}
set_entry_block(block);
bool in_try = false;
IRList::iterator next;
DexPosition* current_position = nullptr;
DexPosition* last_pos_before_this_block = nullptr;
for (auto it = ir->begin(); it != ir->end(); it = next) {
next = std::next(it);
if (it->type == MFLOW_TRY) {
if (it->tentry->type == TRY_START) {
// Assumption: TRY_STARTs are only at the beginning of blocks
always_assert(!m_editable || it == block_begin);
always_assert(m_editable || it == block->m_begin);
in_try = true;
} else if (it->tentry->type == TRY_END) {
try_ends.emplace_back(it->tentry, block);
in_try = false;
}
} else if (it->type == MFLOW_CATCH) {
try_catches[it->centry] = block;
} else if (it->type == MFLOW_TARGET) {
branch_to_targets[it->target->src].emplace_back(block, &*it);
} else if (it->type == MFLOW_POSITION) {
current_position = it->pos.get();
}
if (!end_of_block(ir, it, in_try)) {
continue;
}
// End the current block.
if (m_editable) {
// Steal the code from the ir and put it into the block.
// This is safe to do while iterating in ir because iterators in ir now
// point to elements of block->m_entries (and we already computed next).
block->m_entries.splice_selection(block->m_entries.end(), *ir,
block_begin, next);
if (last_pos_before_this_block != nullptr) {
auto first_insn = block->get_first_insn_before_position();
if (first_insn != block->end()) {
// DexPositions apply to every instruction in the linear stream until
// the next DexPosition. Because we're breaking up the linear stream
// into many small blocks, we need to make sure that instructions stay
// associated with the same DexPosition as they were in the input
// IRList.
//
// This creates duplicate positions, but we will remove any extras at
// linearize time.
block->m_entries.insert_before(
first_insn,
std::make_unique<DexPosition>(*last_pos_before_this_block));
}
}
} else {
block->m_end = next;
}
if (next == ir->end()) {
break;
}
// Start a new block at the next MethodItem.
block = create_block();
if (m_editable) {
last_pos_before_this_block = current_position;
block_begin = next;
} else {
block->m_begin = next;
}
}
TRACE(CFG, 5, " build: boundaries found");
}
// Link the blocks together with edges. If the CFG is editable, also insert
// fallthrough goto instructions and delete MFLOW_TARGETs.
void ControlFlowGraph::connect_blocks(BranchToTargets& branch_to_targets) {
for (auto it = m_blocks.begin(); it != m_blocks.end(); ++it) {
// Set outgoing edge if last MIE falls through
Block* b = it->second;
auto& last_mie = *b->rbegin();
bool fallthrough = true;
if (last_mie.type == MFLOW_OPCODE) {
auto last_op = last_mie.insn->opcode();
if (opcode::is_branch(last_op)) {
fallthrough = !opcode::is_goto(last_op);
auto const& target_blocks = branch_to_targets[&last_mie];
for (auto& p : target_blocks) {
auto target_block = p.first;
auto& target_mie = *p.second;
always_assert(target_mie.type == MFLOW_TARGET);
always_assert(target_mie.target->src == &last_mie);
Edge::MaybeCaseKey case_key;
if (target_mie.target->type == BRANCH_MULTI) {
always_assert_log(opcode::is_switch(last_mie.insn->opcode()),
"block %zu in %s\n", target_block->id(),
SHOW(*this));
case_key = target_mie.target->case_key;
} else {
always_assert(target_mie.target->type == BRANCH_SIMPLE);
}
if (m_editable) {
// The the branch information is stored in the edges, we don't need
// the targets inside the blocks anymore
target_block->m_entries.erase_and_dispose(
target_block->m_entries.iterator_to(target_mie));
}
if (case_key) {
add_edge(b, target_block, *case_key);
continue;
}
auto edge_type = opcode::is_goto(last_op) ? EDGE_GOTO : EDGE_BRANCH;
add_edge(b, target_block, edge_type);
}
if (m_editable && opcode::is_goto(last_op)) {
// We don't need the gotos in editable mode because the edges
// fully encode that information
delete last_mie.insn;
b->m_entries.erase_and_dispose(b->m_entries.iterator_to(last_mie));
}
} else if (opcode::is_a_return(last_op) || last_op == OPCODE_THROW) {
fallthrough = false;
}
}
auto next = std::next(it);
if (fallthrough && next != m_blocks.end()) {
Block* next_b = next->second;
TRACE(CFG, 6, "adding fallthrough goto %zu -> %zu", b->id(),
next_b->id());
add_edge(b, next_b, EDGE_GOTO);
}
}
TRACE(CFG, 5, " build: edges added");
}
void ControlFlowGraph::add_catch_edges(TryEnds& try_ends,
TryCatches& try_catches) {
/*
* Every block inside a try-start/try-end region
* gets an edge to every catch block. This simplifies dataflow analysis
* since you can always get the exception state by looking at successors,
* without any additional analysis.
*
* NB: This algorithm assumes that a try-start/try-end region will consist of
* sequentially-numbered blocks, which is guaranteed because catch regions
* are contiguous in the bytecode, and we generate blocks in bytecode order.
*/
for (auto tep : try_ends) {
auto try_end = tep.first;
auto tryendblock = tep.second;
size_t bid = tryendblock->id();
while (true) {
Block* block = m_blocks.at(bid);
if (ends_with_may_throw(block)) {
uint32_t i = 0;
for (auto mie = try_end->catch_start; mie != nullptr;
mie = mie->centry->next) {
auto catchblock = try_catches.at(mie->centry);
// Create a throw edge with the information from this catch entry
add_edge(block, catchblock, mie->centry->catch_type, i);
++i;
}
}
auto block_begin = block->begin();
if (block_begin != block->end() && block_begin->type == MFLOW_TRY) {