From de9ad98d2d6358e6aa773f0bb5258b629bde9389 Mon Sep 17 00:00:00 2001 From: Matthias Braun Date: Wed, 11 May 2022 08:41:09 -0700 Subject: [PATCH] Fix endless loop in optimizePhiConst with integer constant switch condition Avoid endless loop in degenerate case with an integer constant as switch condition as reported in https://reviews.llvm.org/D124552 --- llvm/lib/CodeGen/CodeGenPrepare.cpp | 6 +++- .../CodeGenPrepare/X86/switch-phi-const.ll | 29 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/llvm/lib/CodeGen/CodeGenPrepare.cpp b/llvm/lib/CodeGen/CodeGenPrepare.cpp index 2fd9be8c4c219..813fbd1956f94 100644 --- a/llvm/lib/CodeGen/CodeGenPrepare.cpp +++ b/llvm/lib/CodeGen/CodeGenPrepare.cpp @@ -7037,9 +7037,13 @@ bool CodeGenPrepare::optimizeSwitchPhiConstants(SwitchInst *SI) { // change the code to: // switch(x) { case 42: phi(x, ...) } + Value *Condition = SI->getCondition(); + // Avoid endless loop in degenerate case. + if (isa(*Condition)) + return false; + bool Changed = false; BasicBlock *SwitchBB = SI->getParent(); - Value *Condition = SI->getCondition(); Type *ConditionType = Condition->getType(); for (const SwitchInst::CaseHandle &Case : SI->cases()) { diff --git a/llvm/test/Transforms/CodeGenPrepare/X86/switch-phi-const.ll b/llvm/test/Transforms/CodeGenPrepare/X86/switch-phi-const.ll index 5dd53a6892245..2854cd02c935b 100644 --- a/llvm/test/Transforms/CodeGenPrepare/X86/switch-phi-const.ll +++ b/llvm/test/Transforms/CodeGenPrepare/X86/switch-phi-const.ll @@ -126,3 +126,32 @@ case_13: default: ret void } + +define void @switch_phi_const_degenerate() { +; CHECK-LABEL: @switch_phi_const_degenerate( +; CHECK-NEXT: bb0: +; CHECK-NEXT: br i1 undef, label [[CASE_42:%.*]], label [[BB1:%.*]] +; CHECK: bb1: +; CHECK-NEXT: br label [[CASE_42]] +; CHECK: case_42: +; CHECK-NEXT: [[X:%.*]] = phi i32 [ 0, [[BB0:%.*]] ], [ 42, [[BB1]] ] +; CHECK-NEXT: store volatile i32 [[X]], i32* @effect, align 4 +; CHECK-NEXT: ret void +; +bb0: + br i1 undef, label %case_42, label %bb1 + +bb1: + switch i32 42, label %unreachable [ + i32 42, label %case_42 + ] + +case_42: + ; We should not end up in an endless loop 42 with the switch condition 42. + %x = phi i32 [0, %bb0], [42, %bb1] + store volatile i32 %x, i32* @effect, align 4 + ret void + +unreachable: + unreachable +}