-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchow.cc
More file actions
1481 lines (1362 loc) · 44.6 KB
/
Copy pathchow.cc
File metadata and controls
1481 lines (1362 loc) · 44.6 KB
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
/*====================================================================
* chow.cc
*
* contains an implementation of the chow register allocation
* algorithm.
*====================================================================
********************************************************************/
/*-----------------------MODULE INCLUDES-----------------------*/
#include <Shared.h>
#include <SSA.h>
#include <algorithm>
#include <utility>
#include <map>
#include <stack>
#include <queue>
#include "chow.h"
#include "chow_extensions.h"
#include "params.h"
#include "live_range.h"
#include "live_unit.h"
#include "union_find.h"
#include "rc.h" //RegisterClass definitions
#include "assign.h" //Handles some aspects of register assignment
#include "cfg_tools.h"
#include "spill.h"
#include "color.h"
#include "stats.h"
#include "mapping.h"
#include "cleave.h"
#include "depths.h" //for computing loop nesting depth
#include "shared_globals.h" //Global namespace for iloc Shared vars
#include "rematerialize.h" //Global namespace for iloc Shared vars
#include "heuristics.h" //heuristics for splitting, etc.
#include "reach.h"
/*------------------MODULE LOCAL DEFINITIONS-------------------*/
namespace {
/* local functions */
void assert_same_orig_name(LRID,Variable,SparseSet,Block* b);
void MoveLoadsAndStores();
unsigned int FindLiveRanges(Arena uf_arena);
void CreateLiveRanges(Arena arena, Unsigned_Int num_lrs);
void SplitNeighbors(LiveRange*, LRSet*, LRSet*);
void UpdateConstrainedLists(LiveRange* , LiveRange* , LRSet*, LRSet*);
void UpdateConstrainedListsAfterDelete(LiveRange*, LRSet*, LRSet*);
LiveUnit* AddLiveUnitOnce(LRID, Block*, SparseSet, Variable);
LiveRange* ComputePriorityAndChooseTop(LRSet*, LRSet*);
void BuildInitialLiveRanges(Arena);
void BuildInterferences(Arena arena);
void AllocateRegisters();
void RenameRegisters();
bool ShouldSplitLiveRange(LiveRange* lr);
inline void AddToCorrectConstrainedList(LRSet*,LRSet*,LiveRange*);
void CountLocals();
void DumpLocals();
void SeparateConstrainedLiveRanges(LRSet*, LRSet*);
void ColorUnconstrained(LRSet* unconstr_lrs);
void PullNodeFromGraph(LiveRange* lr, LRSet* constr_lrs);
bool LiveIn(LRID orig_lrid, Block* blk);
}
/*--------------------BEGIN IMPLEMENTATION---------------------*/
namespace Chow {
/* globals */
Arena arena;
LRVec live_ranges;
std::vector<std::vector<LiveUnit*> > live_units;
std::map<Variable,bool> local_names;
std::stack<LiveRange*> color_stack;
}
void Chow::Run()
{
//--- Initialization for building live ranges ---//
//arena for all chow memory allocations
if(arena == NULL){arena = Arena_Create(); }
//--- Build live ranges ---//
BuildInitialLiveRanges(arena);
//DumpLocals();
if(Debug::dot_dump_lr){
LiveRange* lr = live_ranges[Debug::dot_dump_lr];
Debug::DotDumpLR(lr, "initial");
Debug::dot_dumped_lrs.push_back(lr);
}
//--- Initialization for allocating registers ---//
//compute loop nesting depth needed for computing priorities
find_nesting_depths(arena); Globals::depths = depths;
Spill::Init(arena);
if(Params::Algorithm::move_loads_and_stores)
{
//clear out edge extensions
Block* b;
Edge* e;
ForAllBlocks(b)
{
Block_ForAllPreds(e,b) e->edge_extension = NULL;
Block_ForAllSuccs(e,b) e->edge_extension = NULL;
}
}
//--- Run the priority algorithm ---//
Stats::Start("Allocate Registers");
AllocateRegisters();
if(Debug::dot_dump_lr) Debug::DotDumpFinalLRs();
Stats::Stop();
Stats::Start("Rename Registers");
RenameRegisters();
Stats::Stop();
}
/*-----------------INTERNAL MODULE FUNCTIONS-------------------*/
namespace {
/*
*=======================
* AllocateRegisters()
*=======================
*
* Does the actual register allocation
*
***/
void AllocateRegisters()
{
using Chow::live_ranges;
LiveRange* lr;
LRSet constr_lrs;
LRSet unconstr_lrs;
//the register that holds the frame pointer is not a candidate for
//allocation since it resides in a special reserved register. remove
//this from the interference graph
live_ranges[Spill::frame.lrid]->MarkNonCandidateAndDelete();
//separate unconstrained live ranges
SeparateConstrainedLiveRanges(&constr_lrs, &unconstr_lrs);
//assign registers to constrained live ranges
lr = NULL;
while(!(constr_lrs.empty()))
{
//steps 2: (a) - (c)
lr = ComputePriorityAndChooseTop(&constr_lrs, &unconstr_lrs);
if(lr == NULL)
{
debug("No more constrained lrs can be assigned");
break;
}
lr->AssignColor();
debug("LR: %d is top priority, given color: %d", lr->id, lr->color);
SplitNeighbors(lr, &constr_lrs, &unconstr_lrs);
}
//assign registers to unconstrained live ranges
debug("assigning unconstrained live ranges colors");
ColorUnconstrained(&unconstr_lrs);
//record some statistics about the allocation
Stats::chowstats.clrFinal = live_ranges.size();
}
/*
*=======================================
* ComputePriorityAndChooseTop()
*=======================================
*
***/
LiveRange*
ComputePriorityAndChooseTop(LRSet* constr_lrs, LRSet* unconstr_lrs)
{
std::vector<LiveRange*> deletes;
//compute priority for all live ranges
for(LRSet::iterator i = constr_lrs->begin(); i != constr_lrs->end(); i++)
{
LiveRange* lr = *i;
assert(lr->is_candidate);
//priority has never been computed
if(lr->priority == LiveRange::UNDEFINED_PRIORITY)
{
lr->ComputePriority();
debug("priority for LR: %d is %.3f", lr->id, lr->priority);
//check to see if this live range is a non-candidate for
//allocation. I think we need to only check this the first time
//we compute the priority function. if the priority changes due
//to a live range split it should be reset to undefined so we
//can compute it again.
if(lr->priority <= 0.0 || lr->IsEntirelyUnColorable())
{
deletes.push_back(lr);
}
}
}
//remove any live ranges not deemed worthy
for(unsigned int i = 0; i < deletes.size(); i++)
{
LiveRange* lr = deletes[i];
lr->MarkNonCandidateAndDelete(); Stats::chowstats.cSpills++;
UpdateConstrainedListsAfterDelete(lr, constr_lrs, unconstr_lrs);
}
//find the top priority live range
float top_prio = -3.4e38; //a very small number
LiveRange* top_lr = NULL;
for(LRSet::iterator i = constr_lrs->begin(); i != constr_lrs->end(); i++)
{
LiveRange* lr = *i;
//see if this live range has a greater priority
if(lr->priority > top_prio)
{
top_prio = lr->priority;
top_lr = lr;
}
}
if(top_lr != NULL)
{
debug("top priority is %.3f LR: %d", top_prio, top_lr->id);
constr_lrs->erase(top_lr);
}
return top_lr;
}
/*
*=============================
* BuildInitialLiveRanges()
*=============================
* Each live range starts out where no definition reaches a use
* outside the live range. This means that no stores will be necessary
* at first. When we allocate a register it will stay across the
* entire live range.
*
* If a successor block needs a load then we must generate a store
*
* If the def reaches a use outside the live range we must generate a
* store.
*
*
*/
void BuildInitialLiveRanges(Arena chow_arena)
{
using Chow::live_ranges;
//run union find over phi nodes to get initial live ranges
Stats::Start("Create LiveRanges");
unsigned int clrInitial = FindLiveRanges(chow_arena);
--clrInitial; //no lr for SSA name 0
debug("SSA NAMES: %d", SSA_def_count);
debug("UNIQUE LRs: %d", clrInitial);
Stats::chowstats.clrInitial = clrInitial;
//create a mapping from ssa names to live range ids
Mapping::CreateLiveRangeNameMap(chow_arena);
Mapping::CreateLiveRangeTypeMap(chow_arena, clrInitial);
Mapping::ConvertLiveInNamespaceSSAToLiveRange();
//initialize coloring structures based on number of register classes
Coloring::Init(chow_arena, clrInitial);
//now that we know how many live ranges we start with allocate them
Stats::ComputeBBStats(chow_arena, SSA_def_count);
CreateLiveRanges(chow_arena, clrInitial);
Stats::Stop();
//find all interferenes for each live range
Stats::Start("Build Interferences");
BuildInterferences(chow_arena);
Stats::Stop();
if(Params::Algorithm::rematerialize)
{
Stats::Start("Split Rematerializable");
//run through and find the live ranges that are rematerializable
//and set the appropriate flags. these may exist separately from
//the split live ranges if the entire live range is
//rematerialiazible. so we set them all in this loop. if we split
//out part that is not rematerializable it will be set in th
//function below
for(unsigned int ssa_name = 0; ssa_name < SSA_def_count; ssa_name++)
{
if(Remat::tags[ssa_name].val == Remat::CONST)
{
LRID lrid = Mapping::SSAName2OrigLRID(ssa_name);
live_ranges[lrid]->rematerializable = true;
live_ranges[lrid]->remat_op = Remat::tags[ssa_name].op;
}
}
Remat::SplitRematerializableLiveRanges();
Stats::chowstats.clrRemat = live_ranges.size();
Stats::Stop();
}
//compute where the loads and stores need to go in the live range
for(LRVec::size_type i = 0; i < live_ranges.size(); i++)
live_ranges[i]->MarkLoadsAndStores();
Debug::LiveRange_DDumpAll(&live_ranges);
}
/*
*=============================
* FindLiveRanges()
*=============================
* Uses a fast union find algorithm to union phi-params to find out
* which values belong in the same live range
*
*/
unsigned int FindLiveRanges(Arena uf_arena)
{
UFSets_Init(uf_arena, SSA_def_count);
if(Params::Algorithm::rematerialize)
{
Remat::ComputeTags();
Remat::remat_sets = UFSet_Create(SSA_def_count);
}
Block* b;
Phi_Node* phi;
UFSet* set;
unsigned int liverange_count = SSA_def_count;
ForAllBlocks(b)
{
//visit each phi node and union the parameters and destination
//register together since they should all be part of the same live
//range
Block_ForAllPhiNodes(phi, b)
{
debug("process phi: %d at %s (%d)", phi->new_name, bname(b), bid(b));
Variable* v_ptr;
//find current sets for the phi node
set = Find_Set(phi->new_name);
Phi_Node_ForAllParms(v_ptr, phi)
{
Variable v = *v_ptr;
if(v != 0)
{
//union sets together unless they are alredy part of the
//same live range
if(set != Find_Set(v))
{
set = UFSet_Union(set, Find_Set(v));
--liverange_count;
debug("union: %d U %d = %d(setid)", phi->new_name, v, set->id);
}
if(Params::Algorithm::rematerialize)
{
UFSet* remat_set = Find_Set(phi->new_name, Remat::remat_sets);
//selectively union if using rematerialization
if(Remat::tags[v].val == Remat::tags[phi->new_name].val)
{
debug("live range union ok by remat: %d",v);
remat_set =
UFSet_Union(remat_set, Find_Set(v, Remat::remat_sets));
}
else //split live ranges
{
debug("live range split by remat: %d",v);
Remat::AddSplit(phi->new_name, v);
}
}
}
}
}
}
return liverange_count;
}
/*
*=============================
* BuildInterferences()
*=============================
* Construct the interferences for each live range
*
*/
void BuildInterferences(Arena arena)
{
using Chow::live_ranges;
using Mapping::SSAName2OrigLRID;
//build the interference graph
//find all live ranges that are referenced or live out in this
//block. those are the live ranges that need to include this block.
//each of those live ranges will interfere with every other live
//range in the block. walk through the graph and examine each block
//to build the live ranges
LiveRange* lr;
LRID lrid;
Block* blk;
Inst* inst;
Operation** op;
Unsigned_Int* reg;
SparseSet lrset = SparseSet_Create(arena, live_ranges.size());
ForAllBlocks(blk)
{
debug("processing blk:%s (%d)", bname(blk), bid(blk));
//we need to acccount for any variable that is referenced in this
//block as it may not be in the live_out set, but should still be
//included in the live range if it is referenced in this block. A
//name may be in a live range under more than one original name.
//for example when a name is defined in two branches of an if
//statement it will be added to the live range by that definition,
//but will also be live out in those blocks under a different name
//(the name defined by the phi-node for those definitions). as
//long as we get the last definition in the block we should be ok
SparseSet_Clear(lrset);
Block_ForAllInstsReverse(inst, blk)
{
//go in reverse because we want the last def that we see to be
//the orig_name for the live range, this must be so because we
//use that name in the use-def chains to decide where to put a
//store for the defs of a live range
debug("processing inst:\n%s", Debug::StringOfInst(inst));
Inst_ForAllOperations(op, inst)
{
Operation_ForAllDefs(reg, *op)
{
lrid = SSAName2OrigLRID(*reg);
//better not have two definitions in the same block for the
//same live range
assert_same_orig_name(lrid, *reg, lrset, blk);
AddLiveUnitOnce(lrid, blk, lrset, *reg);
debug("(def) %d (lrid) as r%d", lrid,*reg);
}
Operation_ForAllUses(reg, *op)
{
lrid = SSAName2OrigLRID(*reg);
AddLiveUnitOnce(lrid, blk, lrset, *reg);
debug("(use) %d (lrid) as r%d", lrid,*reg);
}
}
}
//Now add in the live_out set to the variables that include this
//block in their live range
Liveness_Info info;
info = SSA_live_out[bid(blk)];
for(unsigned int j = 0; j < info.size; j++)
{
//add block to each live range
lrid = SSAName2OrigLRID(info.names[j]);
AddLiveUnitOnce(lrid, blk, lrset, info.names[j]);
debug("(liveout) %d (lrid) as r%d", lrid, info.names[j]);
}
//now that we have the full set of lrids that need to include this
//block we can add the live units to the live ranges and update
//the interference graph
Unsigned_Int v, i;
debug("LIVE SIZE: %d\n", SparseSet_Size(lrset));
SparseSet_ForAll(v, lrset)
{
lr = live_ranges[v];
//update the interference lists
SparseSet_ForAll(i, lrset)
{
if(v == i) continue; //skip yourself
//add interference if in the same class
LiveRange* lrT = live_ranges[i];
if(lr->rc == lrT->rc)
{
//debug("%d conflicts with %d", v, i);
lr->AddInterference(lrT);
}
}
}
}
}
/*
*============================
* CreateLiveRanges()
*============================
* Allocates space for initial live ranges and sets default values.
*
***/
void CreateLiveRanges(Arena arena, Unsigned_Int num_lrs)
{
using Chow::live_ranges;
using Chow::live_units;
//initialize LiveRange class
LiveRange::Init(arena, num_lrs);
//create initial live ranges
live_ranges.resize(num_lrs, NULL); //allocate space for live ranges
live_units.resize(block_count+1);
for(unsigned int lrid = 0; lrid < num_lrs; lrid++)
{
LiveRange* lr =
new LiveRange(RegisterClass::InitialRegisterClassForLRID(lrid),
lrid,
Mapping::LiveRangeDefType(lrid),
num_lrs);
//initialize blockmap here since there should only be one tied to
//the original live range that is shared by all live ranges split
//from this one
lr->blockmap = new std::map<unsigned int, LiveRange*>;
lr->splits = new std::vector<LiveRange*>;
live_ranges[lrid] = lr;
}
}
//make sure that if we have already added a live unit for this lrid
//that the original name matches this name. this is important for the
//rewriting step, but this check does not need to be made when adding
//from the live_out set since those names may be different but it is
//ok because they occur in a different block
void assert_same_orig_name(LRID lrid, Variable v, SparseSet set,
Block* b)
{
if(SparseSet_Member(set,lrid))
{
LiveUnit* unit = Chow::live_ranges[lrid]->LiveUnitForBlock(b);
//debug("already present: %d, orig_name: %d new_orig: %d block: %s (%d)",
// lrid, unit->orig_name, v, bname(b), bid(b));
assert(unit->orig_name == v);
}
}
/*
*=============================
* AddLiveUnitOnce()
*=============================
*
* adds the block to the live range, but only once depending on the
* contents of the *lrset*
* returns the new LiveUnit or NULL if it is already in the live range
***/
LiveUnit*
AddLiveUnitOnce(LRID lrid, Block* b, SparseSet lrset, Variable orig_name)
{
//debug("ADDING: %d BLOCK: %s (%d)", lrid, bname(b), bid(b));
LiveUnit* new_unit = NULL;
if(!SparseSet_Member(lrset, lrid))
{
bool do_add = true;
LiveRange* lr = Chow::live_ranges[lrid];
if(Chow::local_names[orig_name])
{
lr->is_local = true;
do_add = Params::Algorithm::allocate_locals;
}
if(do_add)
{
SparseSet_Insert(lrset, lrid);
Stats::BBStats bbstat = Stats::GetStatsForBlock(b, lr->id);
new_unit = lr->AddLiveUnitForBlock(b, orig_name, bbstat);
Chow::live_units[bid(b)].push_back(new_unit);
}
//block map must be initialized regardless of local or not
(*(lr->blockmap))[bid(b)] = lr;
}
return new_unit;
}
/*
*============================
* SplitNeighbors()
*============================
*
* Checks a live range for neighbors that need to be split because we
* just assigned a color to this live range. a neighbor will need to
* be split when its forbidden set is equal to the set of all
* registers.
*
* splitting the neighbors may shuffle them around on the constrained
* and unconstrained lists so we pass them in for possible
* modification.
***/
void SplitNeighbors(LiveRange* lr, LRSet* constr_lr, LRSet* unconstr_lr)
{
debug("BEGIN SPLITTING");
using Stats::chowstats;
using Params::Algorithm::spill_instead_of_split;
using Params::Algorithm::split_limit;
//make a copy of the interference list as a worklist since splitting
//may add and remove items to the original interference list
LRVec worklist(lr->fear_list->size());
if(lr->fear_list->size() > 0)
{
copy(lr->fear_list->begin(), lr->fear_list->end(), worklist.begin());
}
//our neighbors are the live ranges we interfere with
while(!worklist.empty())
{
LiveRange* intf_lr = worklist.back(); worklist.pop_back();
//only check allocation candidates, may not be a candidate if it
//has already been assigned a color
if(!(intf_lr->is_candidate)) continue;
//split if no registers available
if(ShouldSplitLiveRange(intf_lr))
{
debug("Need to split LR: %d", intf_lr->id);
if((split_limit && (int)chowstats.cSplits >= split_limit) ||
spill_instead_of_split ||
intf_lr->IsEntirelyUnColorable())
{
debug("LR: %d is uncolorable - will not split", intf_lr->id);
//delete this live range from the interference graph. update
//the constrained lists since live ranges may shuffle around
//after we delete this from the interference graph
intf_lr->MarkNonCandidateAndDelete(); chowstats.cSpills++;
UpdateConstrainedListsAfterDelete(intf_lr, constr_lr, unconstr_lr);
}
else //try to split
{
//Split() returns the new live range that we know is colorable
LiveRange* newlr = intf_lr->Split();
//add new liverange to list of live ranges
Chow::live_ranges.push_back(newlr);
assert(newlr->id == (Chow::live_ranges.size() - 1));
debug("ADDED LR: %d", newlr->id);
if(intf_lr->IsZeroOccurrence())
{
intf_lr->MarkNonCandidateAndDelete(); chowstats.cZeroOccurrence++;
UpdateConstrainedListsAfterDelete(intf_lr, constr_lr, unconstr_lr);
if(Params::Algorithm::optimistic && !newlr->IsConstrained())
PullNodeFromGraph(newlr, constr_lr);
else
AddToCorrectConstrainedList(constr_lr, unconstr_lr, newlr);
}
else
{
//make sure constrained lists are up-to-date after split
UpdateConstrainedLists(newlr, intf_lr, constr_lr, unconstr_lr);
//if the remainder of the live range we just split from
//interferes with the live range we assigned a color to then
//add it to the work list because it may need to be split more
if(intf_lr->InterferesWith(lr))
{
if(!Params::Algorithm::optimistic ||
(Params::Algorithm::optimistic && !intf_lr->simplified))
{
worklist.push_back(intf_lr);
}
}
}
debug("split complete for LR: %d", intf_lr->id);
Debug::LiveRange_DDump(intf_lr);
Debug::LiveRange_DDump(newlr);
}
}
}
debug("DONE SPLITTING");
}
/*
*================================
* UpdateConstrainedLists()
*================================
* Makes sure that the live ranges are in the constrained lists if
* they are constrained. This is used to update the lists after a live
* range split for the live ranges that interfere with both the old
* and the new live range.
*
***/
void UpdateConstrainedLists(LiveRange* newlr,
LiveRange* origlr,
LRSet* constr_lrs,
LRSet* unconstr_lrs)
{
//if optimistic
//if origlr is no longer constraiend then remove from constraiend
//and pull the node out of the graph. next check what needs to be
//done with the new live range.
if(Params::Algorithm::optimistic)
{
if(!origlr->IsConstrained())
{
constr_lrs->erase(origlr);
PullNodeFromGraph(origlr, constr_lrs);
}
if(newlr->IsConstrained())
{
constr_lrs->insert(newlr);
}
else
{
PullNodeFromGraph(newlr, constr_lrs);
}
return; //exit early
}
//update constrained lists, only need to update for any live range
//that interferes with both the new and original live range because
//those are the only live ranges that could have changed status
/*LRSet updates;
set_intersection(newlr->fear_list->begin(), newlr->fear_list->end(),
origlr->fear_list->begin(), origlr->fear_list->end(),
inserter(updates,updates.begin()));
for(LRSet::iterator i = updates.begin(); i != updates.end(); i++)
*/
for(LazySet::iterator i = newlr->fear_list->begin();
i != newlr->fear_list->end();
i++)
{
LiveRange* lr = *i;
if(origlr->fear_list->member(lr))
{
//skip anyone that has already been assigned a color
if(!lr->is_candidate) continue;
if(lr->IsConstrained())
{
debug("ensuring LR: %d is in constr", lr->id);
unconstr_lrs->erase(lr);
constr_lrs->insert(lr);
}
}
}
//also, need to update the new and original live range positions
AddToCorrectConstrainedList(constr_lrs, unconstr_lrs, newlr);
if(!origlr->IsConstrained())
{
debug("shifting LR: %d to unconstrained", origlr->id);
constr_lrs->erase(origlr);
unconstr_lrs->insert(origlr);
}
}
/*
*====================================
* UpdateConstrainedListsAfterDelete()
*====================================
* Updates the lists after a live range is deleted from the
* interference graph to ensure that the live range is in the correct
* bucket.
***/
void UpdateConstrainedListsAfterDelete(LiveRange* lr,
LRSet* constr_lrs,
LRSet* unconstr_lrs)
{
for(LazySet::iterator i = lr->fear_list->begin();
i != lr->fear_list->end();
i++)
{
LiveRange* fear_lr = *i;
//skip anyone that has already been assigned a color
if(!(fear_lr)->is_candidate) continue;
if((fear_lr)->IsConstrained())
{
if(unconstr_lrs->erase(fear_lr))
constr_lrs->insert(fear_lr);
}
else
{
if(constr_lrs->erase(fear_lr))
{
if(Params::Algorithm::optimistic)
PullNodeFromGraph(fear_lr, constr_lrs);
else
unconstr_lrs->insert(fear_lr);
}
}
}
constr_lrs->erase(lr);
}
/*
*===================
* RenameRegisters()
*===================
* Renames the variables in the code to use the registers assigned by
* coloring
***/
void RenameRegisters()
{
using Mapping::SSAName2OrigLRID;
using Assign::GetMachineRegAssignment;
using Assign::ResetFreeTmpRegs;
using Assign::EnsureReg;
using Assign::HandleCopy;
using Assign::UnEvict;
using Assign::InitLocalAllocation;
debug("allocation complete. renaming registers...");
Assign::Init(Chow::arena);
//stack pointer is the initial size of the stack frame
debug("STACK: %d", Spill::frame.stack_pointer);
Block* b;
Inst* inst;
Operation** op;
Unsigned_Int* reg;
std::vector<Register> instUses;
std::vector<Register> instDefs;
ForAllBlocks(b)
{
InitLocalAllocation(b);
Block_ForAllInsts(inst, b)
{
debug("renaming inst:\n%s", Debug::StringOfInst(inst));
/* collect a list of uses and defs used in this regist that is
* used in algorithms when deciding which registers can be
* evicted for temporary uses */
instUses.clear();
instDefs.clear();
Inst_ForAllOperations(op, inst)
{
Operation_ForAllUses(reg, *op)
{
LRID lrid = SSAName2OrigLRID(*reg);
instUses.push_back(lrid);
}
Operation_ForAllDefs(reg, *op)
{
LRID lrid = SSAName2OrigLRID(*reg);
instDefs.push_back(lrid);
}
}
/* rename uses and then defs */
//we need to keep the original inst separate. when we call
//ensure_reg_assignment it may be the case that we insert some
//stores after this instruction. we don't want to process those
//store instructions in the register allocator so we have to
//update the value of the inst pointer. thus we keep origInst
//and updatedInst separate.
Inst* origInst = inst;
Inst** updatedInst = &inst;
Inst_ForAllOperations(op, inst)
{
//treat copies special so that we don't load and then copy,
//but rather just load into the dest if needed
if(opcode_specs[(*op)->opcode].details & COPY)
{
HandleCopy(b, origInst, updatedInst, op, instUses, instDefs);
}
else
{
Operation_ForAllUses(reg, *op)
{
//make sure the live range is in a register
EnsureReg(reg, b, origInst, updatedInst,
*op, FOR_USE,
instUses, instDefs);
}
Operation_ForAllDefs(reg, *op)
{
//make sure the live range is in a register
EnsureReg(reg, b, origInst, updatedInst,
*op, FOR_DEF,
instUses, instDefs);
}
}
}
UnEvict(updatedInst);
}
//make available the tmp regs used in this block
ResetFreeTmpRegs(b);
}
//if we are to optimize positions of loads and stores, do so after
//assigning registers
if(Params::Algorithm::move_loads_and_stores)
{
debug("moving loads and stores to \"optimal\" position");
MoveLoadsAndStores();
}
//finally rewrite the frame statement to have the first register be
//the frame pointer and to adjust the stack size
Spill::RewriteFrameOp();
}
/*
*=======================
* MoveLoadsAndStores()
*=======================
* Moves the loads and stores to a better position so that they might
* be executed less times.
*
* IMPORTANT NOTE: This function must be called after the RenameRegisters
* function. The reason is that we are inserting loads and stores for
* MACHINE REGISTERS, not for SSA names. We have to do this because we
* keep a map from <block id, lrid> --> allocated color. Since we are
* moving instructions to different blocks and possibly adding blocks
* this map would be difficult to maintain. So we solve that by simply
* moving the stores and loads after renaming and using the machine
* register assignments
***/
void HandleCopyDefs();
void MoveLoadsAndStores()
{
using namespace std; //for list, pair
typedef list<MovedSpillDescription>::iterator LI;
InitCFGTools(Chow::arena); //for adding edges
//first handle any copy-def spills so that they are turned into
//normal copies and stores placed on the edges as needed
HandleCopyDefs();
//we should already have the loads and stores moved onto the
//appropriate edge. all that remains is to walk the graph and
//actually insert the instructions, splitting edges as needed.
Block* blk;
Boolean need_reorder = FALSE;
ForAllBlocks(blk)
{
Edge* edg;
Block_ForAllSuccs(edg, blk)
{
//if edg->edge_extension is not NULL then there is a load or
//store moved onto this edge and we must process it
if(edg->edge_extension)
{
//first we look at whether we need to split this edge in order
//to move the loads and stores to their destinations
//we need to split the block if:
//1) we are inserting a store and the successor has more than
//one pred
//2) we are inserting a load and the predecessor has more than
//one successor
//3) we are inserting a copy and the successor has more than
//one pred
Boolean need_split = FALSE;
for(LI ee = edg->edge_extension->spill_list->begin();
ee != edg->edge_extension->spill_list->end();
ee++)
{
MovedSpillDescription msd = (*ee);
switch(msd.spill_type){
case STORE_SPILL:
if(Block_PredCount(edg->succ) > 1)
{
need_split = TRUE;
}
break;
case LOAD_SPILL:
if(Block_SuccCount(edg->pred) > 1)
{
need_split = TRUE;
break;
}
case COPY_SPILL:
{
//in the case of a copy, we always split the edge
//because we want the copy to come after all of the
//stores and the easiest way to do that is split the
//edge and insert the copy in the same manner as a ld
need_split = true;
break;
}
default:
error("got invalid spill type: %d", msd.spill_type);
assert(false);
}
if(need_split) break; //out of loop
}
//split edge if needed
Block* blkLD = edg->pred;
Block* blkST = edg->succ;
if(need_split || Params::Algorithm::enhanced_code_motion)
{
Block* blkT = SplitEdge(edg->pred, edg->succ);
blkLD = blkST = blkT;
need_reorder = TRUE;
}
//enhanced code motion attempts to replace a load/store pair
//on an edge with a copy
if(Params::Algorithm::enhanced_code_motion)
{
Chow::Extensions::EnhancedCodeMotion(edg, blkLD);
}