Skip to content

[LoopInterchange] Fix overflow in cost calculation #111807

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions llvm/include/llvm/Analysis/LoopCacheAnalysis.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

#include "llvm/Analysis/LoopAnalysisManager.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Support/InstructionCost.h"
#include <optional>

namespace llvm {
Expand All @@ -31,7 +32,7 @@ class ScalarEvolution;
class SCEV;
class TargetTransformInfo;

using CacheCostTy = int64_t;
using CacheCostTy = InstructionCost;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to now just obscure the concrete type?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe. I personally don't mind the CacheCostTy alias here, think it is quite appropriately named. Thinking about it, maybe it's actually a better name than using InstructionCost here? But I don't have strong opinions so certainly don't mind a search/replace of CacheCostTy with InstructionCost assuming that's what you're suggesting, is that right @fhahn ?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personally I find it more inconvenient to hide the actual type behind another level of indirection, but changing it in this patch would unnecessarily increase the diff.

using LoopVectorTy = SmallVector<Loop *, 8>;

/// Represents a memory reference as a base pointer and a set of indexing
Expand Down Expand Up @@ -192,8 +193,6 @@ class CacheCost {
using LoopCacheCostTy = std::pair<const Loop *, CacheCostTy>;

public:
static CacheCostTy constexpr InvalidCost = -1;

/// Construct a CacheCost object for the loop nest described by \p Loops.
/// The optional parameter \p TRT can be used to specify the max. distance
/// between array elements accessed in a loop so that the elements are
Expand Down
12 changes: 9 additions & 3 deletions llvm/lib/Analysis/LoopCacheAnalysis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,8 @@ CacheCostTy IndexedReference::computeRefCost(const Loop &L,
const SCEV *TripCount =
computeTripCount(*AR->getLoop(), *Sizes.back(), SE);
Type *WiderType = SE.getWiderType(RefCost->getType(), TripCount->getType());
// For the multiplication result to fit, request a type twice as wide.
WiderType = WiderType->getExtendedType();
RefCost = SE.getMulExpr(SE.getNoopOrZeroExtend(RefCost, WiderType),
SE.getNoopOrZeroExtend(TripCount, WiderType));
}
Expand All @@ -338,14 +340,18 @@ CacheCostTy IndexedReference::computeRefCost(const Loop &L,
assert(RefCost && "Expecting a valid RefCost");

// Attempt to fold RefCost into a constant.
// CacheCostTy is a signed integer, but the tripcount value can be large
// and may not fit, so saturate/limit the value to the maximum signed
// integer value.
if (auto ConstantCost = dyn_cast<SCEVConstant>(RefCost))
return ConstantCost->getValue()->getZExtValue();
return ConstantCost->getValue()->getLimitedValue(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this still needed or sufficient to let wrapping handle by InstructionCost?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this is unfortunately still needed. Helper getZExtValue() returns an uint64_t and checks if the value fits in this number of bits.

std::numeric_limits<int64_t>::max());

LLVM_DEBUG(dbgs().indent(4)
<< "RefCost is not a constant! Setting to RefCost=InvalidCost "
"(invalid value).\n");

return CacheCost::InvalidCost;
return CacheCostTy::getInvalid();
}

bool IndexedReference::tryDelinearizeFixedSize(
Expand Down Expand Up @@ -696,7 +702,7 @@ CacheCostTy
CacheCost::computeLoopCacheCost(const Loop &L,
const ReferenceGroupsTy &RefGroups) const {
if (!L.isLoopSimplifyForm())
return InvalidCost;
return CacheCostTy::getInvalid();

LLVM_DEBUG(dbgs() << "Considering loop '" << L.getName()
<< "' as innermost loop.\n");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
; RUN: opt < %s -passes='print<loop-cache-cost>' -disable-output 2>&1 | FileCheck %s

; For a loop with a very large iteration count, make sure the cost
; calculation does not overflow:
;
; void a(int b) {
; for (int c;; c += b)
; for (long d = 0; d < -3ULL; d += 2ULL)
; A[c][d][d] = 0;
; }

; CHECK: Loop 'outer.loop' has cost = 9223372036854775807
; CHECK: Loop 'inner.loop' has cost = 9223372036854775807

@A = local_unnamed_addr global [11 x [11 x [11 x i32]]] zeroinitializer, align 16

define void @foo(i32 noundef %b) {
entry:
%0 = sext i32 %b to i64
br label %outer.loop

outer.loop:
%indvars.iv = phi i64 [ %indvars.iv.next, %outer.loop.cleanup ], [ 0, %entry ]
br label %inner.loop

outer.loop.cleanup:
%indvars.iv.next = add nsw i64 %indvars.iv, %0
br label %outer.loop

inner.loop:
%inner.iv = phi i64 [ 0, %outer.loop ], [ %add, %inner.loop ]
%arrayidx3 = getelementptr inbounds [11 x [11 x [11 x i32]]], ptr @A, i64 0, i64 %indvars.iv, i64 %inner.iv, i64 %inner.iv
store i32 0, ptr %arrayidx3, align 4
%add = add nuw i64 %inner.iv, 2
%cmp = icmp ult i64 %inner.iv, -5
br i1 %cmp, label %inner.loop, label %outer.loop.cleanup
}
Loading