Index: lib/Transforms/Utils/LoopUnrollRuntime.cpp =================================================================== --- lib/Transforms/Utils/LoopUnrollRuntime.cpp +++ lib/Transforms/Utils/LoopUnrollRuntime.cpp @@ -295,10 +295,13 @@ if (isa(BECount) || !BECount->getType()->isIntegerTy()) return false; - // Add 1 since the backedge count doesn't include the first loop iteration + // Add 1 since the backedge count doesn't include the first loop iteration. const SCEV *TripCountSC = SE->getAddExpr(BECount, SE->getConstant(BECount->getType(), 1)); - if (isa(TripCountSC)) + + // If the trip count is not computable, zero, or the preceding add caused an + // overflow of the SCEV (causing a zero trip count), then don't unroll. + if (isa(TripCountSC) || TripCountSC->isZero()) return false; // We only handle cases when the unroll factor is a power of 2. Index: test/Transforms/LoopUnroll/runtime-zero-tripcount.ll =================================================================== --- test/Transforms/LoopUnroll/runtime-zero-tripcount.ll +++ test/Transforms/LoopUnroll/runtime-zero-tripcount.ll @@ -0,0 +1,33 @@ +; RUN: opt < %s -S -loop-unroll -unroll-runtime | FileCheck %s + +; PR21409 ( http://llvm.org/bugs/show_bug.cgi?id=21409 ) +; Don't unroll a loop with a zero trip count. +; Either the loop is never entered, or the calculation of the +; trip count overflowed. + +define i32 @zero_trip_count() { +entry: + br label %while.body + +while.body: + %d = phi i32 [ 0, %entry ], [ %inc, %while.body ] + %inc = add i32 %d, 1 + %cmp = icmp eq i32 %inc, 0 + br i1 %cmp, label %while.end, label %while.body + +while.end: + ret i32 0 + +; CHECK-LABEL: zero_trip_count( +; CHECK: entry: +; CHECK-NEXT: br label %while.body +; CHECK: while.body: +; CHECK-NEXT: %d = phi i32 [ 0, %entry ], [ %inc, %while.body ] +; CHECK-NEXT: %inc = add i32 %d, 1 +; CHECK-NEXT: %cmp = icmp eq i32 %inc, 0 +; CHECK-NEXT: br i1 %cmp, label %while.end, label %while.body +; CHECK: while.end: +; CHECK-NEXT: ret i32 0 +} + +