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