@@ -116,6 +116,12 @@ class SILGlobalOpt {
116
116
bool run ();
117
117
118
118
protected:
119
+ // / Reset all the maps of global variables.
120
+ void reset ();
121
+
122
+ // / Collect all global variables.
123
+ void collect ();
124
+
119
125
// / If this is a call to a global initializer, map it.
120
126
void collectGlobalInitCall (ApplyInst *AI);
121
127
@@ -807,11 +813,12 @@ bool SILGlobalOpt::tryRemoveGlobalAddr(SILGlobalVariable *global) {
807
813
return false ;
808
814
809
815
for (auto *addr : GlobalAddrMap[global]) {
810
- eraseUsesOfInstruction (addr, [](SILInstruction *) {} );
816
+ eraseUsesOfInstruction (addr);
811
817
addr->eraseFromParent ();
812
818
}
813
819
814
- GlobalAddrMap.erase (global);
820
+ reset ();
821
+ collect ();
815
822
return true ;
816
823
}
817
824
@@ -821,7 +828,8 @@ bool SILGlobalOpt::tryRemoveGlobalAlloc(SILGlobalVariable *global,
821
828
return false ;
822
829
823
830
alloc->eraseFromParent ();
824
- AllocGlobalStore.erase (global);
831
+ reset ();
832
+ collect ();
825
833
return true ;
826
834
}
827
835
@@ -1002,7 +1010,16 @@ void SILGlobalOpt::optimizeGlobalAccess(SILGlobalVariable *SILG,
1002
1010
1003
1011
}
1004
1012
1005
- bool SILGlobalOpt::run () {
1013
+ void SILGlobalOpt::reset () {
1014
+ AllocGlobalStore.clear ();
1015
+ GlobalVarStore.clear ();
1016
+ GlobalAddrMap.clear ();
1017
+ GlobalAccessMap.clear ();
1018
+ GlobalLoadMap.clear ();
1019
+ GlobalInitCallMap.clear ();
1020
+ }
1021
+
1022
+ void SILGlobalOpt::collect () {
1006
1023
for (auto &F : *Module) {
1007
1024
// TODO: Add support for ownership.
1008
1025
if (F.hasOwnership ()) {
@@ -1038,7 +1055,13 @@ bool SILGlobalOpt::run() {
1038
1055
}
1039
1056
}
1040
1057
}
1058
+ }
1059
+
1060
+ bool SILGlobalOpt::run () {
1061
+ // Collect all the global variables and associated instructions.
1062
+ collect ();
1041
1063
1064
+ // Optimize based on what we just collected.
1042
1065
for (auto &InitCalls : GlobalInitCallMap) {
1043
1066
// Don't optimize functions that are marked with the opt.never attribute.
1044
1067
bool shouldOptimize = true ;
@@ -1086,10 +1109,13 @@ bool SILGlobalOpt::run() {
1086
1109
HasChanged |= tryRemoveGlobalAlloc (alloc.first , alloc.second );
1087
1110
}
1088
1111
1112
+ // Copy the globals so we don't get issues with modifying while iterating.
1113
+ SmallVector<SILGlobalVariable *, 12 > globals;
1089
1114
for (auto &global : Module->getSILGlobals ()) {
1090
- // TODO: For some reaons, if we keep iterating through `getSILGlobals`
1091
- // after `tryRemoveUnusedGlobal` is called, we gen an error.
1092
- HasChanged |= tryRemoveUnusedGlobal (&global);
1115
+ globals.push_back (&global);
1116
+ }
1117
+ for (auto *global : globals) {
1118
+ HasChanged |= tryRemoveUnusedGlobal (global);
1093
1119
}
1094
1120
1095
1121
return HasChanged;
0 commit comments