@@ -850,17 +850,17 @@ static bool CanMergeValues(Value *First, Value *Second) {
850
850
// / branch to Succ, into Succ.
851
851
// /
852
852
// / Assumption: Succ is the single successor for BB.
853
- static bool CanPropagatePredecessorsForPHIs (BasicBlock *BB, BasicBlock *Succ) {
853
+ static bool
854
+ CanPropagatePredecessorsForPHIs (BasicBlock *BB, BasicBlock *Succ,
855
+ const SmallPtrSetImpl<BasicBlock *> &BBPreds) {
854
856
assert (*succ_begin (BB) == Succ && " Succ is not successor of BB!" );
855
857
856
858
LLVM_DEBUG (dbgs () << " Looking to fold " << BB->getName () << " into "
857
859
<< Succ->getName () << " \n " );
858
860
// Shortcut, if there is only a single predecessor it must be BB and merging
859
861
// is always safe
860
- if (Succ->getSinglePredecessor ()) return true ;
861
-
862
- // Make a list of the predecessors of BB
863
- SmallPtrSet<BasicBlock*, 16 > BBPreds (pred_begin (BB), pred_end (BB));
862
+ if (Succ->getSinglePredecessor ())
863
+ return true ;
864
864
865
865
// Look at all the phi nodes in Succ, to see if they present a conflict when
866
866
// merging these blocks
@@ -1000,16 +1000,47 @@ static void replaceUndefValuesInPhi(PHINode *PN,
1000
1000
}
1001
1001
}
1002
1002
1003
+ // Only when they shares a single common predecessor, return true.
1004
+ // Only handles cases when BB can't be merged while its predecessors can be
1005
+ // redirected.
1006
+ static bool
1007
+ CanRedirectPredsOfEmptyBBToSucc (BasicBlock *BB, BasicBlock *Succ,
1008
+ const SmallPtrSetImpl<BasicBlock *> &BBPreds,
1009
+ const SmallPtrSetImpl<BasicBlock *> &SuccPreds,
1010
+ BasicBlock *&CommonPred) {
1011
+
1012
+ // There must be phis in BB, otherwise BB will be merged into Succ directly
1013
+ if (BB->phis ().empty () || Succ->phis ().empty ())
1014
+ return false ;
1015
+
1016
+ // BB must have predecessors not shared that can be redirected to Succ
1017
+ if (!BB->hasNPredecessorsOrMore (2 ))
1018
+ return false ;
1019
+
1020
+ // Get single common predecessors of both BB and Succ
1021
+ for (BasicBlock *SuccPred : SuccPreds) {
1022
+ if (BBPreds.count (SuccPred)) {
1023
+ if (CommonPred)
1024
+ return false ;
1025
+ CommonPred = SuccPred;
1026
+ }
1027
+ }
1028
+
1029
+ return true ;
1030
+ }
1031
+
1003
1032
// / Replace a value flowing from a block to a phi with
1004
1033
// / potentially multiple instances of that value flowing from the
1005
1034
// / block's predecessors to the phi.
1006
1035
// /
1007
1036
// / \param BB The block with the value flowing into the phi.
1008
1037
// / \param BBPreds The predecessors of BB.
1009
1038
// / \param PN The phi that we are updating.
1039
+ // / \param CommonPred The common predecessor of BB and PN's BasicBlock
1010
1040
static void redirectValuesFromPredecessorsToPhi (BasicBlock *BB,
1011
1041
const PredBlockVector &BBPreds,
1012
- PHINode *PN) {
1042
+ PHINode *PN,
1043
+ BasicBlock *CommonPred) {
1013
1044
Value *OldVal = PN->removeIncomingValue (BB, false );
1014
1045
assert (OldVal && " No entry in PHI for Pred BB!" );
1015
1046
@@ -1037,26 +1068,39 @@ static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
1037
1068
// will trigger asserts if we try to clean it up now, without also
1038
1069
// simplifying the corresponding conditional branch).
1039
1070
BasicBlock *PredBB = OldValPN->getIncomingBlock (i);
1071
+
1072
+ if (PredBB == CommonPred)
1073
+ continue ;
1074
+
1040
1075
Value *PredVal = OldValPN->getIncomingValue (i);
1041
- Value *Selected = selectIncomingValueForBlock (PredVal, PredBB,
1042
- IncomingValues);
1076
+ Value *Selected =
1077
+ selectIncomingValueForBlock (PredVal, PredBB, IncomingValues);
1043
1078
1044
1079
// And add a new incoming value for this predecessor for the
1045
1080
// newly retargeted branch.
1046
1081
PN->addIncoming (Selected, PredBB);
1047
1082
}
1083
+ if (CommonPred)
1084
+ PN->addIncoming (OldValPN->getIncomingValueForBlock (CommonPred), BB);
1085
+
1048
1086
} else {
1049
1087
for (unsigned i = 0 , e = BBPreds.size (); i != e; ++i) {
1050
1088
// Update existing incoming values in PN for this
1051
1089
// predecessor of BB.
1052
1090
BasicBlock *PredBB = BBPreds[i];
1053
- Value *Selected = selectIncomingValueForBlock (OldVal, PredBB,
1054
- IncomingValues);
1091
+
1092
+ if (PredBB == CommonPred)
1093
+ continue ;
1094
+
1095
+ Value *Selected =
1096
+ selectIncomingValueForBlock (OldVal, PredBB, IncomingValues);
1055
1097
1056
1098
// And add a new incoming value for this predecessor for the
1057
1099
// newly retargeted branch.
1058
1100
PN->addIncoming (Selected, PredBB);
1059
1101
}
1102
+ if (CommonPred)
1103
+ PN->addIncoming (OldVal, BB);
1060
1104
}
1061
1105
1062
1106
replaceUndefValuesInPhi (PN, IncomingValues);
@@ -1067,13 +1111,30 @@ bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
1067
1111
assert (BB != &BB->getParent ()->getEntryBlock () &&
1068
1112
" TryToSimplifyUncondBranchFromEmptyBlock called on entry block!" );
1069
1113
1070
- // We can't eliminate infinite loops.
1114
+ // We can't simplify infinite loops.
1071
1115
BasicBlock *Succ = cast<BranchInst>(BB->getTerminator ())->getSuccessor (0 );
1072
- if (BB == Succ) return false ;
1116
+ if (BB == Succ)
1117
+ return false ;
1118
+
1119
+ SmallPtrSet<BasicBlock *, 16 > BBPreds (pred_begin (BB), pred_end (BB));
1120
+ SmallPtrSet<BasicBlock *, 16 > SuccPreds (pred_begin (Succ), pred_end (Succ));
1073
1121
1074
- // Check to see if merging these blocks would cause conflicts for any of the
1075
- // phi nodes in BB or Succ. If not, we can safely merge.
1076
- if (!CanPropagatePredecessorsForPHIs (BB, Succ)) return false ;
1122
+ // The single common predecessor of BB and Succ when BB cannot be killed
1123
+ BasicBlock *CommonPred = nullptr ;
1124
+
1125
+ bool BBKillable = CanPropagatePredecessorsForPHIs (BB, Succ, BBPreds);
1126
+
1127
+ // Even if we can not fold bB into Succ, we may be able to redirect the
1128
+ // predecessors of BB to Succ.
1129
+ bool BBPhisMergeable =
1130
+ BBKillable ||
1131
+ CanRedirectPredsOfEmptyBBToSucc (BB, Succ, BBPreds, SuccPreds, CommonPred);
1132
+
1133
+ if (!BBKillable && !BBPhisMergeable)
1134
+ return false ;
1135
+
1136
+ // Check to see if merging these blocks/phis would cause conflicts for any of
1137
+ // the phi nodes in BB or Succ. If not, we can safely merge.
1077
1138
1078
1139
// Check for cases where Succ has multiple predecessors and a PHI node in BB
1079
1140
// has uses which will not disappear when the PHI nodes are merged. It is
@@ -1102,6 +1163,11 @@ bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
1102
1163
}
1103
1164
}
1104
1165
1166
+ if (BBPhisMergeable && CommonPred)
1167
+ LLVM_DEBUG (dbgs () << " Found Common Predecessor between: " << BB->getName ()
1168
+ << " and " << Succ->getName () << " : "
1169
+ << CommonPred->getName () << " \n " );
1170
+
1105
1171
// 'BB' and 'BB->Pred' are loop latches, bail out to presrve inner loop
1106
1172
// metadata.
1107
1173
//
@@ -1174,25 +1240,37 @@ bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
1174
1240
if (PredTI->hasMetadata (LLVMContext::MD_loop))
1175
1241
return false ;
1176
1242
1177
- LLVM_DEBUG (dbgs () << " Killing Trivial BB: \n " << *BB);
1243
+ if (BBKillable)
1244
+ LLVM_DEBUG (dbgs () << " Killing Trivial BB: \n " << *BB);
1245
+ else if (BBPhisMergeable)
1246
+ LLVM_DEBUG (dbgs () << " Merge Phis in Trivial BB: \n " << *BB);
1178
1247
1179
1248
SmallVector<DominatorTree::UpdateType, 32 > Updates;
1249
+
1180
1250
if (DTU) {
1181
1251
// To avoid processing the same predecessor more than once.
1182
1252
SmallPtrSet<BasicBlock *, 8 > SeenPreds;
1183
- // All predecessors of BB will be moved to Succ.
1184
- SmallPtrSet<BasicBlock *, 8 > PredsOfSucc ( pred_begin ( Succ), pred_end (Succ));
1253
+ // All predecessors of BB (except the common predecessor) will be moved to
1254
+ // Succ.
1185
1255
Updates.reserve (Updates.size () + 2 * pred_size (BB) + 1 );
1186
- for (auto *PredOfBB : predecessors (BB))
1187
- // This predecessor of BB may already have Succ as a successor.
1188
- if (!PredsOfSucc.contains (PredOfBB))
1256
+
1257
+ for (auto *PredOfBB : predecessors (BB)) {
1258
+ // Do not modify those common predecessors of BB and Succ
1259
+ if (!SuccPreds.contains (PredOfBB))
1189
1260
if (SeenPreds.insert (PredOfBB).second )
1190
1261
Updates.push_back ({DominatorTree::Insert, PredOfBB, Succ});
1262
+ }
1263
+
1191
1264
SeenPreds.clear ();
1265
+
1192
1266
for (auto *PredOfBB : predecessors (BB))
1193
- if (SeenPreds.insert (PredOfBB).second )
1267
+ // When BB cannot be killed, do not remove the edge between BB and
1268
+ // CommonPred.
1269
+ if (SeenPreds.insert (PredOfBB).second && PredOfBB != CommonPred)
1194
1270
Updates.push_back ({DominatorTree::Delete, PredOfBB, BB});
1195
- Updates.push_back ({DominatorTree::Delete, BB, Succ});
1271
+
1272
+ if (BBKillable)
1273
+ Updates.push_back ({DominatorTree::Delete, BB, Succ});
1196
1274
}
1197
1275
1198
1276
if (isa<PHINode>(Succ->begin ())) {
@@ -1204,21 +1282,19 @@ bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
1204
1282
// Loop over all of the PHI nodes in the successor of BB.
1205
1283
for (BasicBlock::iterator I = Succ->begin (); isa<PHINode>(I); ++I) {
1206
1284
PHINode *PN = cast<PHINode>(I);
1207
-
1208
- redirectValuesFromPredecessorsToPhi (BB, BBPreds, PN);
1285
+ redirectValuesFromPredecessorsToPhi (BB, BBPreds, PN, CommonPred);
1209
1286
}
1210
1287
}
1211
1288
1212
1289
if (Succ->getSinglePredecessor ()) {
1213
1290
// BB is the only predecessor of Succ, so Succ will end up with exactly
1214
1291
// the same predecessors BB had.
1215
-
1216
1292
// Copy over any phi, debug or lifetime instruction.
1217
1293
BB->getTerminator ()->eraseFromParent ();
1218
1294
Succ->splice (Succ->getFirstNonPHI ()->getIterator (), BB);
1219
1295
} else {
1220
1296
while (PHINode *PN = dyn_cast<PHINode>(&BB->front ())) {
1221
- // We explicitly check for such uses in CanPropagatePredecessorsForPHIs .
1297
+ // We explicitly check for such uses for merging phis .
1222
1298
assert (PN->use_empty () && " There shouldn't be any uses here!" );
1223
1299
PN->eraseFromParent ();
1224
1300
}
@@ -1231,21 +1307,35 @@ bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
1231
1307
for (BasicBlock *Pred : predecessors (BB))
1232
1308
Pred->getTerminator ()->setMetadata (LLVMContext::MD_loop, LoopMD);
1233
1309
1234
- // Everything that jumped to BB now goes to Succ.
1235
- BB->replaceAllUsesWith (Succ);
1236
- if (!Succ->hasName ()) Succ->takeName (BB);
1237
-
1238
- // Clear the successor list of BB to match updates applying to DTU later.
1239
- if (BB->getTerminator ())
1240
- BB->back ().eraseFromParent ();
1241
- new UnreachableInst (BB->getContext (), BB);
1242
- assert (succ_empty (BB) && " The successor list of BB isn't empty before "
1243
- " applying corresponding DTU updates." );
1310
+ if (BBKillable) {
1311
+ // Everything that jumped to BB now goes to Succ.
1312
+ BB->replaceAllUsesWith (Succ);
1313
+
1314
+ if (!Succ->hasName ())
1315
+ Succ->takeName (BB);
1316
+
1317
+ // Clear the successor list of BB to match updates applying to DTU later.
1318
+ if (BB->getTerminator ())
1319
+ BB->back ().eraseFromParent ();
1320
+
1321
+ new UnreachableInst (BB->getContext (), BB);
1322
+ assert (succ_empty (BB) && " The successor list of BB isn't empty before "
1323
+ " applying corresponding DTU updates." );
1324
+ } else if (BBPhisMergeable) {
1325
+ // Everything except CommonPred that jumped to BB now goes to Succ.
1326
+ BB->replaceUsesWithIf (Succ, [BBPreds, CommonPred](Use &U) -> bool {
1327
+ if (Instruction *UseInst = dyn_cast<Instruction>(U.getUser ()))
1328
+ return UseInst->getParent () != CommonPred &&
1329
+ BBPreds.contains (UseInst->getParent ());
1330
+ return false ;
1331
+ });
1332
+ }
1244
1333
1245
1334
if (DTU)
1246
1335
DTU->applyUpdates (Updates);
1247
1336
1248
- DeleteDeadBlock (BB, DTU);
1337
+ if (BBKillable)
1338
+ DeleteDeadBlock (BB, DTU);
1249
1339
1250
1340
return true ;
1251
1341
}
0 commit comments