diff --git a/llvm/include/llvm/ADT/Cleanup.h b/llvm/include/llvm/ADT/Cleanup.h new file mode 100644 --- /dev/null +++ b/llvm/include/llvm/ADT/Cleanup.h @@ -0,0 +1,44 @@ +//===- Cleanup.h - Run a lambda when a fn exits -----------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// Cleanup is an RAII type whose destructor runs an arbitrary function or +/// lambda. You can use this to do some work at the end of a function, right +/// before it returns. +/// +/// Prior art: absl::Cleanup. +/// +/// Example:: +/// +/// Cleanup cleanup = [&] { close(fd); }; +/// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_ADT_CLEANUP_H +#define LLVM_ADT_CLEANUP_H + +#include +namespace llvm { + +template class Cleanup { +public: + Cleanup(FnT Fn) : Fn(std::move(Fn)) {} + ~Cleanup() { Fn(); } + +private: + static_assert(std::is_same_v()()), void>, + "Callback function must return void."); + + FnT Fn; +}; + +template Cleanup(FnT Fn) -> Cleanup; + +} // end namespace llvm + +#endif // LLVM_ADT_CLEANUP_H diff --git a/llvm/unittests/ADT/CMakeLists.txt b/llvm/unittests/ADT/CMakeLists.txt --- a/llvm/unittests/ADT/CMakeLists.txt +++ b/llvm/unittests/ADT/CMakeLists.txt @@ -15,6 +15,7 @@ BitVectorTest.cpp BreadthFirstIteratorTest.cpp BumpPtrListTest.cpp + CleanupTest.cpp CoalescingBitVectorTest.cpp CombinationGeneratorTest.cpp DAGDeltaAlgorithmTest.cpp diff --git a/llvm/unittests/ADT/CleanupTest.cpp b/llvm/unittests/ADT/CleanupTest.cpp new file mode 100644 --- /dev/null +++ b/llvm/unittests/ADT/CleanupTest.cpp @@ -0,0 +1,25 @@ +//===- llvm/unittest/Support/CleanupTest.cpp - Cleanup tests ---===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "llvm/ADT/Cleanup.h" +#include "gtest/gtest.h" +#include + +using namespace llvm; + +namespace { + +TEST(CleanupTest, Simple) { + bool ran = false; + { + Cleanup c = [&] { ran = true; }; + } + EXPECT_TRUE(ran); +} + +} // anonymous namespace