Skip to content

Commit

Permalink
Re-import LLVMSupport from llvm-project and enforce header includes o…
Browse files Browse the repository at this point in the history
…nly being used from the Swift fork when building stdlib (swiftlang#40173)

* Enforce using headers from Swift's LLVMSupport fork and not llvm-project when building stdlib

* [LLVMSupport] Re-import LLVMSupport .cpp and .h files from 9ff3a9759b7c2f146e7f46e4aebc60453c577c5a from apple/llvm-project

Done via the following commands, while having llvm-project checked out at 9ff3a9759b7c2f146e7f46e4aebc60453c577c5a, a
commit on the stable/20210726 branch of apple/llvm-project, <swiftlang/llvm-project@9ff3a97>:

for i in swift/stdlib/public/LLVMSupport/*.cpp ; do cp llvm-project/llvm/lib/Support/$(basename $i) $i ; done
for i in swift/stdlib/include/llvm/ADT/*.h; do cp llvm-project/llvm/include/llvm/ADT/$(basename $i) $i ; done
for i in swift/stdlib/include/llvm/Support/*.h; do cp llvm-project/llvm/include/llvm/Support/$(basename $i) $i ; done
cp llvm-project/llvm/include/llvm/ADT/ScopeExit.h swift/stdlib/include/llvm/ADT/ScopeExit.h
cp llvm-project/llvm/include/llvm/ADT/Twine.h swift/stdlib/include/llvm/ADT/Twine.h
cp llvm-project/llvm/include/llvm/Support/raw_ostream.h swift/stdlib/include/llvm/Support/raw_ostream.h

* [LLVMSupport] Re-namespace the LLVMSupport fork after re-forking by re-applying b72788c

More precisely:

1) git cherry-pick b72788c
2) manually resolve the conflict in AlignOf.h by keeping the HEAD's version of the chunk and discarding the cherry-pick's change
3) git add AlignOf.h
4) git status | grep "deleted by us" | awk '{print($4)}' | xargs git rm
5) git cherry-pick --continue

Original namespacing commit message:

> This adds the `__swift::__runtime` inline namespace to the LLVMSupport
> interfaces.  This avoids an ODR violation when LLVM and Swift are in the
> same address space.  It also will aid in the process of pruning the
> LLVMSupport library by ensuring that accidental leakage of the llvm
> namespace does not allow us to remove symbols which we rely on.

* [LLVMSupport] Re-apply "pruning" on re-forked LLVMSupport from bb10270

This re-applies the "pruning" commit from bb10270, which did the following:
- Remove many whole files,
- Remove "epoch tracking" and "reverse iteration" support from ADT containers
- Remove "ABI break checking" support from STLExtras
- Remove float parsing functions from StringExtras.h
- Remove APInt/APSInt dependencies from StringRef.h + StringRef.cpp (edit distance, int parsing)
- Remove some variants of error handling and dependency of dbgs() from ErrorHandling.h and ErrorHandling.cpp

We don't need to do the whole-file-removal step, because that's already done, but the rest is re-applied by doing:

1) git cherry-pick bb10270
2) manually resolving conflict in ADT/DenseMap.h by keeping HEAD's version of the chunk and removing epoch tracking from it
3) manually resolving conflict in ADT/STLExtras.h by keeping HEAD's version of the chunk and removing ABI check checking from it
4) manually resolving conflict in ADT/StringExtras.h by deleting the whole chunk (removing APInt/APSInt dependent functions)
5) manually resolving conflict in ErrorHandling.cpp by force-applying the cherry-pick's version (removing write() calls and OOM callback)
6) manually resolving the three conflicts in CMakeLists.txt files by keeping HEAD's version completely
7) git add stdlib/include/llvm/{ADT/StringSwitch.h,ADT/Twine.h,Support/raw_ostream.h}

Original commit description:

> Reduce LLVMSupport to the subset required for the runtime.  This reduces
> the TCB and the overheads of the runtime.  The inline namespace's
> preservation ensures that ODR violations do not occur.

* [LLVMSupport] Re-apply all post-import modifications on LLVMSupport that the Swift's fork has

Since the previous commits re-imported "vanilla" versions of LLVMSupport, we need to re-apply all modifications that the Swift's fork has made since the last import. More precisely:

1) git diff 7b70120..origin/main -- stdlib/include/llvm stdlib/public/LLVMSupport | git apply -3 --exclude "stdlib/include/llvm/Support/DataTypes.h" --exclude "stdlib/include/llvm/Config/llvm-config.h.cmake"
2) manually resolve conflict in STLExtras.h by applying the "__swift::__runtime" prefix to HEAD's version
3) manually resolve conflicts in StringSwitch.h by keeping HEAD's version (removing the Unicode BOM marker at the beginning of the file, keeping LLVM's version of the string functions)
4) manually resolve conflict in SwapByteOrder.h by adding the `defined(__wasi__)` part into the #if

* [LLVMSupport] Drop remaining dependencies on APSInt.h, Error.h, DataTypes.h and STLForwardCompat.h

Most cases can drop the #includes without any changes, in some cases there are
straighforward replacements (climits, cstdint). For STLForwardCompat.h, we need
to bring in parts of STLForwardCompat.h from llvm-project.

* [LLVMSupport] Remove raw_ostream.h and drop dependencies to it from the runtime

* [LLVMSupport] Simplify error reporting in SmallVector and avoid using std::string when producing fatal errors messages

Co-authored-by: Saleem Abdulrasool <[email protected]>
  • Loading branch information
kubamracek and compnerd authored Dec 3, 2021
1 parent 8f50a2a commit 7e33575
Show file tree
Hide file tree
Showing 37 changed files with 1,880 additions and 714 deletions.
3 changes: 3 additions & 0 deletions include/swift/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,9 @@ enum class AssociatedValueCheck {
/// Diagnostic printing of \c StaticSpellingKind.
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, StaticSpellingKind SSK);

/// Diagnostic printing of \c ReferenceOwnership.
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, ReferenceOwnership RO);

/// Encapsulation of the overload signature of a given declaration,
/// which is used to determine uniqueness of a declaration within a
/// given context.
Expand Down
2 changes: 1 addition & 1 deletion include/swift/AST/LayoutConstraintKind.h
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/DataTypes.h"
#include <cstdint>

#ifndef SWIFT_LAYOUT_CONSTRAINTKIND_H
#define SWIFT_LAYOUT_CONSTRAINTKIND_H
Expand Down
4 changes: 0 additions & 4 deletions include/swift/AST/Ownership.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <assert.h>
#include <limits.h>
#include <stdint.h>
Expand Down Expand Up @@ -118,9 +117,6 @@ optionalityOf(ReferenceOwnership ownership) {
llvm_unreachable("impossible");
}

/// Diagnostic printing of \c StaticSpellingKind.
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, ReferenceOwnership RO);

/// Different kinds of value ownership supported by Swift.
enum class ValueOwnership : uint8_t {
/// the context-dependent default ownership (sometimes shared,
Expand Down
7 changes: 7 additions & 0 deletions stdlib/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,13 @@ set(SWIFT_CONCURRENCY_GLOBAL_EXECUTOR
# End of user-configurable options.
#

# Remove llvm-project/llvm/include directory from -I search part when building
# the stdlib. We have our own fork of LLVM includes (Support, ADT) in
# stdlib/include/llvm and we don't want to silently use headers from LLVM.
get_property(stdlib_include_directories DIRECTORY PROPERTY INCLUDE_DIRECTORIES)
list(REMOVE_ITEM stdlib_include_directories "${LLVM_MAIN_INCLUDE_DIR}")
set_property(DIRECTORY PROPERTY INCLUDE_DIRECTORIES ${stdlib_include_directories})

include(AddSwiftStdlib)

# Create convenience targets for the Swift standard library.
Expand Down
55 changes: 51 additions & 4 deletions stdlib/include/llvm/ADT/ArrayRef.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
inline namespace __swift { inline namespace __runtime {
namespace llvm {

template<typename T> struct DenseMapInfo;

/// ArrayRef - Represent a constant reference to an array (0 or more elements
/// consecutively in memory), i.e. a start pointer and a length. It allows
/// various APIs to take consecutive elements easily and conveniently.
Expand All @@ -41,10 +43,17 @@ namespace llvm {
template<typename T>
class LLVM_GSL_POINTER LLVM_NODISCARD ArrayRef {
public:
using iterator = const T *;
using const_iterator = const T *;
using size_type = size_t;
using value_type = T;
using pointer = value_type *;
using const_pointer = const value_type *;
using reference = value_type &;
using const_reference = const value_type &;
using iterator = const_pointer;
using const_iterator = const_pointer;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
using size_type = size_t;
using difference_type = ptrdiff_t;

private:
/// The start of the array, in an external buffer.
Expand Down Expand Up @@ -298,8 +307,17 @@ namespace llvm {
template<typename T>
class LLVM_NODISCARD MutableArrayRef : public ArrayRef<T> {
public:
using iterator = T *;
using value_type = T;
using pointer = value_type *;
using const_pointer = const value_type *;
using reference = value_type &;
using const_reference = const value_type &;
using iterator = pointer;
using const_iterator = const_pointer;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
using size_type = size_t;
using difference_type = ptrdiff_t;

/// Construct an empty MutableArrayRef.
/*implicit*/ MutableArrayRef() = default;
Expand Down Expand Up @@ -554,6 +572,35 @@ namespace llvm {
return hash_combine_range(S.begin(), S.end());
}

// Provide DenseMapInfo for ArrayRefs.
template <typename T> struct DenseMapInfo<ArrayRef<T>> {
static inline ArrayRef<T> getEmptyKey() {
return ArrayRef<T>(
reinterpret_cast<const T *>(~static_cast<uintptr_t>(0)), size_t(0));
}

static inline ArrayRef<T> getTombstoneKey() {
return ArrayRef<T>(
reinterpret_cast<const T *>(~static_cast<uintptr_t>(1)), size_t(0));
}

static unsigned getHashValue(ArrayRef<T> Val) {
assert(Val.data() != getEmptyKey().data() &&
"Cannot hash the empty key!");
assert(Val.data() != getTombstoneKey().data() &&
"Cannot hash the tombstone key!");
return (unsigned)(hash_value(Val));
}

static bool isEqual(ArrayRef<T> LHS, ArrayRef<T> RHS) {
if (RHS.data() == getEmptyKey().data())
return LHS.data() == getEmptyKey().data();
if (RHS.data() == getTombstoneKey().data())
return LHS.data() == getTombstoneKey().data();
return LHS == RHS;
}
};

} // end namespace llvm
}} // namespace swift::runtime

Expand Down
32 changes: 18 additions & 14 deletions stdlib/include/llvm/ADT/DenseMap.h
Original file line number Diff line number Diff line change
Expand Up @@ -381,8 +381,8 @@ class DenseMapBase {
setNumEntries(other.getNumEntries());
setNumTombstones(other.getNumTombstones());

if (is_trivially_copyable<KeyT>::value &&
is_trivially_copyable<ValueT>::value)
if (std::is_trivially_copyable<KeyT>::value &&
std::is_trivially_copyable<ValueT>::value)
memcpy(reinterpret_cast<void *>(getBuckets()), other.getBuckets(),
getNumBuckets() * sizeof(BucketT));
else
Expand Down Expand Up @@ -667,7 +667,7 @@ class DenseMap : public DenseMapBase<DenseMap<KeyT, ValueT, KeyInfoT, BucketT>,
unsigned NumBuckets;

public:
/// Create a DenseMap wth an optional \p InitialReserve that guarantee that
/// Create a DenseMap with an optional \p InitialReserve that guarantee that
/// this number of elements can be inserted in the map without grow()
explicit DenseMap(unsigned InitialReserve = 0) { init(InitialReserve); }

Expand Down Expand Up @@ -864,6 +864,9 @@ class SmallDenseMap
this->insert(I, E);
}

SmallDenseMap(std::initializer_list<typename BaseT::value_type> Vals)
: SmallDenseMap(Vals.begin(), Vals.end()) {}

~SmallDenseMap() {
this->destroyAll();
deallocateBuckets();
Expand Down Expand Up @@ -894,7 +897,7 @@ class SmallDenseMap
std::swap(*LHSB, *RHSB);
continue;
}
// Swap separately and handle any assymetry.
// Swap separately and handle any asymmetry.
std::swap(LHSB->getFirst(), RHSB->getFirst());
if (hasLHSValue) {
::new (&RHSB->getSecond()) ValueT(std::move(LHSB->getSecond()));
Expand Down Expand Up @@ -982,7 +985,7 @@ class SmallDenseMap
if (Small) {
// First move the inline buckets into a temporary storage.
AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer);
BucketT *TmpBegin = reinterpret_cast<BucketT *>(&TmpStorage);
BucketT *TmpEnd = TmpBegin;

// Loop over the buckets, moving non-empty, non-tombstones into the
Expand Down Expand Up @@ -1072,8 +1075,8 @@ class SmallDenseMap
assert(Small);
// Note that this cast does not violate aliasing rules as we assert that
// the memory's dynamic type is the small, inline bucket buffer, and the
// 'storage.buffer' static type is 'char *'.
return reinterpret_cast<const BucketT *>(storage.buffer);
// 'storage' is a POD containing a char buffer.
return reinterpret_cast<const BucketT *>(&storage);
}

BucketT *getInlineBuckets() {
Expand All @@ -1084,7 +1087,7 @@ class SmallDenseMap
const LargeRep *getLargeRep() const {
assert(!Small);
// Note, same rule about aliasing as with getInlineBuckets.
return reinterpret_cast<const LargeRep *>(storage.buffer);
return reinterpret_cast<const LargeRep *>(&storage);
}

LargeRep *getLargeRep() {
Expand Down Expand Up @@ -1130,8 +1133,6 @@ class DenseMapIterator {
friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true>;
friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, false>;

using ConstIterator = DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true>;

public:
using difference_type = ptrdiff_t;
using value_type =
Expand Down Expand Up @@ -1171,11 +1172,14 @@ class DenseMapIterator {
return Ptr;
}

bool operator==(const ConstIterator &RHS) const {
return Ptr == RHS.Ptr;
friend bool operator==(const DenseMapIterator &LHS,
const DenseMapIterator &RHS) {
return LHS.Ptr == RHS.Ptr;
}
bool operator!=(const ConstIterator &RHS) const {
return Ptr != RHS.Ptr;

friend bool operator!=(const DenseMapIterator &LHS,
const DenseMapIterator &RHS) {
return !(LHS == RHS);
}

inline DenseMapIterator& operator++() { // Preincrement
Expand Down
63 changes: 3 additions & 60 deletions stdlib/include/llvm/ADT/DenseMapInfo.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,11 @@
#ifndef LLVM_ADT_DENSEMAPINFO_H
#define LLVM_ADT_DENSEMAPINFO_H

#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/StringRef.h"
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <tuple>
#include <utility>

inline namespace __swift { inline namespace __runtime {
Expand Down Expand Up @@ -257,7 +256,7 @@ template <typename... Ts> struct DenseMapInfo<std::tuple<Ts...>> {
}

template <unsigned I>
static unsigned getHashValueImpl(const Tuple &values, std::true_type) {
static unsigned getHashValueImpl(const Tuple &, std::true_type) {
return 0;
}

Expand All @@ -275,7 +274,7 @@ template <typename... Ts> struct DenseMapInfo<std::tuple<Ts...>> {
}

template <unsigned I>
static bool isEqualImpl(const Tuple &lhs, const Tuple &rhs, std::true_type) {
static bool isEqualImpl(const Tuple &, const Tuple &, std::true_type) {
return true;
}

Expand All @@ -285,62 +284,6 @@ template <typename... Ts> struct DenseMapInfo<std::tuple<Ts...>> {
}
};

// Provide DenseMapInfo for StringRefs.
template <> struct DenseMapInfo<StringRef> {
static inline StringRef getEmptyKey() {
return StringRef(reinterpret_cast<const char *>(~static_cast<uintptr_t>(0)),
0);
}

static inline StringRef getTombstoneKey() {
return StringRef(reinterpret_cast<const char *>(~static_cast<uintptr_t>(1)),
0);
}

static unsigned getHashValue(StringRef Val) {
assert(Val.data() != getEmptyKey().data() && "Cannot hash the empty key!");
assert(Val.data() != getTombstoneKey().data() &&
"Cannot hash the tombstone key!");
return (unsigned)(hash_value(Val));
}

static bool isEqual(StringRef LHS, StringRef RHS) {
if (RHS.data() == getEmptyKey().data())
return LHS.data() == getEmptyKey().data();
if (RHS.data() == getTombstoneKey().data())
return LHS.data() == getTombstoneKey().data();
return LHS == RHS;
}
};

// Provide DenseMapInfo for ArrayRefs.
template <typename T> struct DenseMapInfo<ArrayRef<T>> {
static inline ArrayRef<T> getEmptyKey() {
return ArrayRef<T>(reinterpret_cast<const T *>(~static_cast<uintptr_t>(0)),
size_t(0));
}

static inline ArrayRef<T> getTombstoneKey() {
return ArrayRef<T>(reinterpret_cast<const T *>(~static_cast<uintptr_t>(1)),
size_t(0));
}

static unsigned getHashValue(ArrayRef<T> Val) {
assert(Val.data() != getEmptyKey().data() && "Cannot hash the empty key!");
assert(Val.data() != getTombstoneKey().data() &&
"Cannot hash the tombstone key!");
return (unsigned)(hash_value(Val));
}

static bool isEqual(ArrayRef<T> LHS, ArrayRef<T> RHS) {
if (RHS.data() == getEmptyKey().data())
return LHS.data() == getEmptyKey().data();
if (RHS.data() == getTombstoneKey().data())
return LHS.data() == getTombstoneKey().data();
return LHS == RHS;
}
};

template <> struct DenseMapInfo<hash_code> {
static inline hash_code getEmptyKey() { return hash_code(-1); }
static inline hash_code getTombstoneKey() { return hash_code(-2); }
Expand Down
21 changes: 17 additions & 4 deletions stdlib/include/llvm/ADT/DenseSet.h
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,12 @@ class DenseSetImpl {

Iterator& operator++() { ++I; return *this; }
Iterator operator++(int) { auto T = *this; ++I; return T; }
bool operator==(const ConstIterator& X) const { return I == X.I; }
bool operator!=(const ConstIterator& X) const { return I != X.I; }
friend bool operator==(const Iterator &X, const Iterator &Y) {
return X.I == Y.I;
}
friend bool operator!=(const Iterator &X, const Iterator &Y) {
return X.I != Y.I;
}
};

class ConstIterator {
Expand All @@ -156,8 +160,12 @@ class DenseSetImpl {

ConstIterator& operator++() { ++I; return *this; }
ConstIterator operator++(int) { auto T = *this; ++I; return T; }
bool operator==(const ConstIterator& X) const { return I == X.I; }
bool operator!=(const ConstIterator& X) const { return I != X.I; }
friend bool operator==(const ConstIterator &X, const ConstIterator &Y) {
return X.I == Y.I;
}
friend bool operator!=(const ConstIterator &X, const ConstIterator &Y) {
return X.I != Y.I;
}
};

using iterator = Iterator;
Expand All @@ -174,6 +182,11 @@ class DenseSetImpl {
return ConstIterator(TheMap.find(V));
}

/// Check if the set contains the given element.
bool contains(const_arg_type_t<ValueT> V) const {
return TheMap.find(V) != TheMap.end();
}

/// Alternative version of find() which allows a different, and possibly less
/// expensive, key type.
/// The DenseMapInfo is responsible for supplying methods
Expand Down
Loading

0 comments on commit 7e33575

Please sign in to comment.