diff --git a/llvm/lib/Analysis/ScalarEvolution.cpp b/llvm/lib/Analysis/ScalarEvolution.cpp index 34e497d9ea3cb..8c48ffbf1a049 100644 --- a/llvm/lib/Analysis/ScalarEvolution.cpp +++ b/llvm/lib/Analysis/ScalarEvolution.cpp @@ -15445,6 +15445,12 @@ void ScalarEvolution::LoopGuards::collectFromPHI( const BasicBlock *InBlock = Phi.getIncomingBlock(IncomingIdx); if (!VisitedBlocks.insert(InBlock).second) return {nullptr, scCouldNotCompute}; + + // Avoid analyzing unreachable blocks so that we don't get trapped + // traversing cycles with ill-formed dominance or infinite cycles + if (!SE.DT.isReachableFromEntry(InBlock)) + return {nullptr, scCouldNotCompute}; + auto [G, Inserted] = IncomingGuards.try_emplace(InBlock, LoopGuards(SE)); if (Inserted) collectFromBlock(SE, G->second, Phi.getParent(), InBlock, VisitedBlocks, @@ -15499,6 +15505,9 @@ void ScalarEvolution::LoopGuards::collectFromBlock( ScalarEvolution &SE, ScalarEvolution::LoopGuards &Guards, const BasicBlock *Block, const BasicBlock *Pred, SmallPtrSetImpl &VisitedBlocks, unsigned Depth) { + + assert(SE.DT.isReachableFromEntry(Block) && SE.DT.isReachableFromEntry(Pred)); + SmallVector ExprsToRewrite; auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS, const SCEV *RHS, diff --git a/llvm/test/Analysis/ScalarEvolution/backedge-taken-count-guard-info-with-multiple-predecessors.ll b/llvm/test/Analysis/ScalarEvolution/backedge-taken-count-guard-info-with-multiple-predecessors.ll index 28035b05303db..564ce6b7d622f 100644 --- a/llvm/test/Analysis/ScalarEvolution/backedge-taken-count-guard-info-with-multiple-predecessors.ll +++ b/llvm/test/Analysis/ScalarEvolution/backedge-taken-count-guard-info-with-multiple-predecessors.ll @@ -364,3 +364,29 @@ body: exit: ret void } + +define void @hang_due_to_unreachable_phi_inblock() personality ptr null { +bb: + br label %bb6 + +self-loop: ; preds = %self-loop + %dead = invoke ptr null() + to label %self-loop unwind label %bb4 + +bb4: ; preds = %self-loop + %i5 = landingpad { ptr, i32 } + cleanup + br label %bb6 + +bb6: ; preds = %bb4, %bb + %i7 = phi ptr [ null, %bb4 ], [ null, %bb ] + br label %bb8 + +bb8: ; preds = %bb8, %bb6 + %i9 = phi ptr [ null, %bb8 ], [ null, %bb6 ] + %i11 = icmp eq ptr %i9, null + br i1 %i11, label %bb12, label %bb8 + +bb12: ; preds = %bb8, %bb6 + ret void +}