about summary refs log tree commit diff
path: root/nixpkgs/pkgs/development/compilers/llvm
diff options
context:
space:
mode:
Diffstat (limited to 'nixpkgs/pkgs/development/compilers/llvm')
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/clang-purity.patch22
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/clang-separate-build.patch8
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/clang.nix56
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/default.nix43
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/dragonegg.nix26
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/fix-15974.patch15
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/libc++/darwin.patch30
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/libc++/default.nix53
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/libc++/setup-hook.sh6
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/libc++/xlocale-glibc-2.26.patch17
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/libc++abi/default.nix59
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/lld.nix29
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/lldb.nix44
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/llvm-separate-build.patch12
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/llvm.nix98
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/polly-separate-build.patch12
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.5/polly.nix25
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.7/clang/default.nix60
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.7/clang/purity.patch17
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.7/default.nix59
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/darwin.patch30
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/default.nix47
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/r242056.patch16
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/setup-hook.sh6
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/xlocale-glibc-2.26.patch17
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.7/libc++abi.nix61
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.7/lldb.nix49
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.7/llvm.nix105
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.8/D17533-1.patch60
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.8/clang/default.nix78
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.8/clang/purity.patch17
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.8/default.nix59
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.8/fix-llvm-config.patch11
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.8/libc++/darwin.patch39
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.8/libc++/default.nix52
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.8/libc++/setup-hook.sh6
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.8/libc++abi.nix51
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.8/lldb.nix50
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.8/llvm.nix117
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.9/clang/default.nix79
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.9/clang/purity.patch16
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.9/default.nix59
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.9/libc++/darwin.patch39
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.9/libc++/default.nix51
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.9/libc++/setup-hook.sh6
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.9/libc++/xlocale-glibc-2.26.patch19
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.9/libc++abi.nix51
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.9/lldb.nix56
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.9/llvm-outputs.patch26
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/3.9/llvm.nix171
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/4/clang/default.nix110
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/4/clang/purity.patch16
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/4/cmdline-help.patch39
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/4/default.nix74
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/4/libc++/default.nix58
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/4/libc++/pthread_mach_thread_np.patch41
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/4/libc++/setup-hook.sh6
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/4/libc++/xlocale-glibc-2.26.patch19
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/4/libc++abi.nix51
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/4/lld.nix31
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/4/lldb-libedit.patch30
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/4/lldb.nix62
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/4/llvm-outputs.patch26
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/4/llvm.nix176
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/4/openmp.nix25
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/4/sanitizers-nongnu.patch368
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/5/clang/default.nix106
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/5/clang/purity.patch30
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/5/compiler-rt-codesign.patch155
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/5/compiler-rt.nix37
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/5/default.nix93
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/5/libc++/default.nix52
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/5/libc++/setup-hook.sh6
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/5/libc++abi.nix50
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/5/lld.nix31
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/5/lldb.nix56
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/5/llvm-outputs.patch26
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/5/llvm.nix160
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/5/openmp.nix25
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/5/sanitizers-nongnu.patch370
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/6/clang/default.nix106
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/6/clang/purity.patch30
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/6/compiler-rt-codesign.patch155
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/6/compiler-rt.nix37
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/6/default.nix93
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/6/libc++/default.nix52
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/6/libc++/setup-hook.sh6
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/6/libc++abi.nix50
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/6/lld.nix32
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/6/lldb.nix56
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/6/llvm-outputs.patch26
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/6/llvm.nix173
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/6/openmp.nix25
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/6/sanitizers-nongnu.patch413
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/bintools.nix19
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/clang/default.nix112
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/clang/purity.patch30
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/compiler-rt-clock_gettime.patch74
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/compiler-rt-codesign.patch33
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/compiler-rt.nix61
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/crtbegin-and-end.patch595
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/default.nix149
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/libc++/default.nix50
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/libc++/setup-hook.sh6
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/libc++abi.nix50
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/lld.nix32
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/lldb.nix56
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/llvm-outputs.patch26
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/llvm.nix191
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/openmp.nix25
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/7/sanitizers-nongnu.patch412
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/bintools.nix19
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/clang/clang-xpc.patch41
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/clang/default.nix122
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/clang/purity.patch30
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/clang/static-pie.patch157
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/clang/unwindlib.patch372
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/compiler-rt-clock_gettime.patch74
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/compiler-rt-codesign.patch33
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/compiler-rt.nix66
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/crtbegin-and-end.patch595
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/default.nix193
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/libc++/default.nix51
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/libc++/setup-hook.sh6
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/libc++abi.nix55
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/libunwind.nix22
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/lld.nix32
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/lldb.nix60
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/llvm-outputs.patch26
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/llvm.nix174
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/openmp.nix25
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/8/sanitizers-nongnu.patch412
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/TLI-musl.patch35
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/aarch64.patch51
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/dynamiclibrary-musl.patch33
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/fix-llvm-config.patch13
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/libcxx-0001-musl-hacks.patch39
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/libcxx-max_align_t.patch54
-rw-r--r--nixpkgs/pkgs/development/compilers/llvm/multi.nix48
139 files changed, 10477 insertions, 0 deletions
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/clang-purity.patch b/nixpkgs/pkgs/development/compilers/llvm/3.5/clang-purity.patch
new file mode 100644
index 000000000000..dc3b54e304fc
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/clang-purity.patch
@@ -0,0 +1,22 @@
+diff --git a/lib/Driver/Tools.cpp b/lib/Driver/Tools.cpp
+index 198e82e..810d006 100644
+--- a/lib/Driver/Tools.cpp
++++ b/lib/Driver/Tools.cpp
+@@ -7355,17 +7355,6 @@ void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
+     CmdArgs.push_back("-shared");
+   }
+ 
+-  if (ToolChain.getArch() == llvm::Triple::arm ||
+-      ToolChain.getArch() == llvm::Triple::armeb ||
+-      ToolChain.getArch() == llvm::Triple::thumb ||
+-      ToolChain.getArch() == llvm::Triple::thumbeb ||
+-      (!Args.hasArg(options::OPT_static) &&
+-       !Args.hasArg(options::OPT_shared))) {
+-    CmdArgs.push_back("-dynamic-linker");
+-    CmdArgs.push_back(Args.MakeArgString(
+-        D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
+-  }
+-
+   CmdArgs.push_back("-o");
+   CmdArgs.push_back(Output.getFilename());
+ 
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/clang-separate-build.patch b/nixpkgs/pkgs/development/compilers/llvm/3.5/clang-separate-build.patch
new file mode 100644
index 000000000000..5fb67f169f45
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/clang-separate-build.patch
@@ -0,0 +1,8 @@
+diff -Naur clang-3.4-orig/tools/extra/CMakeLists.txt clang-3.4/tools/extra/CMakeLists.txt
+--- clang-3.4-orig/tools/extra/CMakeLists.txt	2013-11-07 19:08:23.000000000 -0500
++++ clang-3.4/tools/extra/CMakeLists.txt	2014-01-20 11:47:22.678435223 -0500
+@@ -1,3 +1,4 @@
++include(CheckLibraryExists)
+ check_library_exists(edit el_init "" HAVE_LIBEDIT)
+ 
+ add_subdirectory(clang-apply-replacements)
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/clang.nix b/nixpkgs/pkgs/development/compilers/llvm/3.5/clang.nix
new file mode 100644
index 000000000000..7e0163577baf
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/clang.nix
@@ -0,0 +1,56 @@
+{ stdenv, fetch, cmake, libxml2, llvm, version, clang-tools-extra_src }:
+let
+  gcc = if stdenv.cc.isGNU then stdenv.cc.cc else stdenv.cc.cc.gcc;
+in stdenv.mkDerivation {
+  name = "clang-${version}";
+
+  unpackPhase = ''
+    unpackFile ${fetch "cfe" "0846h8vn3zlc00jkmvrmy88gc6ql6014c02l4jv78fpvfigmgssg"}
+    mv cfe-${version}.src clang
+    sourceRoot=$PWD/clang
+    unpackFile ${clang-tools-extra_src}
+    mv clang-tools-extra-* $sourceRoot/tools/extra
+  '';
+
+  buildInputs = [ cmake libxml2 llvm ];
+
+  cmakeFlags = [
+    "-DCMAKE_CXX_FLAGS=-std=c++11"
+  ] ++
+  # Maybe with compiler-rt this won't be needed?
+  (stdenv.lib.optional stdenv.isLinux "-DGCC_INSTALL_PREFIX=${gcc}") ++
+  (stdenv.lib.optional (stdenv.cc.libc != null) "-DC_INCLUDE_DIRS=${stdenv.cc.libc}/include");
+
+  patches = [ ./clang-purity.patch ];
+
+  postPatch = ''
+    sed -i -e 's/Args.hasArg(options::OPT_nostdlibinc)/true/' lib/Driver/Tools.cpp
+    sed -i -e 's/DriverArgs.hasArg(options::OPT_nostdlibinc)/true/' lib/Driver/ToolChains.cpp
+  '';
+
+  # Clang expects to find LLVMgold in its own prefix
+  # Clang expects to find sanitizer libraries in its own prefix
+  postInstall = ''
+    if [ -e ${llvm}/lib/LLVMgold.so ]; then
+      ln -sv ${llvm}/lib/LLVMgold.so $out/lib
+    fi
+
+    ln -sv ${llvm}/lib/clang/${version}/lib $out/lib/clang/${version}/
+    ln -sv $out/bin/clang $out/bin/cpp
+  '';
+
+  enableParallelBuilding = true;
+
+  passthru = {
+    isClang = true;
+  } // stdenv.lib.optionalAttrs stdenv.isLinux {
+    inherit gcc;
+  };
+
+  meta = {
+    description = "A c, c++, objective-c, and objective-c++ frontend for the llvm compiler";
+    homepage    = http://llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/default.nix b/nixpkgs/pkgs/development/compilers/llvm/3.5/default.nix
new file mode 100644
index 000000000000..b87fa747f145
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/default.nix
@@ -0,0 +1,43 @@
+{ pkgs, newScope, stdenv, isl, fetchurl }:
+let
+  callPackage = newScope (self // { inherit stdenv isl version fetch; });
+
+  version = "3.5.2";
+
+  fetch = fetch_v version;
+  fetch_v = ver: name: sha256: fetchurl {
+    url = "https://releases.llvm.org/${ver}/${name}-${ver}.src.tar.xz";
+    inherit sha256;
+  };
+
+  compiler-rt_src = fetch "compiler-rt" "1hsdnzzdr5kglz6fnv3lcsjs222zjsy14y8ax9dy6zqysanplbal";
+  clang-tools-extra_src = fetch "clang-tools-extra" "01607w6hdf1pjgaapn9fy6smk22i3d4ncqjlhk4xi55ifi6kf6pj";
+
+  self = {
+    llvm = callPackage ./llvm.nix rec {
+      version = "3.5.2";
+      fetch = fetch_v version;
+      inherit compiler-rt_src;
+    };
+
+    clang = callPackage ./clang.nix rec {
+      version = "3.5.2";
+      fetch = fetch_v version;
+      inherit clang-tools-extra_src;
+    };
+
+    lld = callPackage ./lld.nix {};
+
+    lldb = callPackage ./lldb.nix {};
+
+    polly = callPackage ./polly.nix {};
+
+    dragonegg = callPackage ./dragonegg.nix {};
+
+    libcxx = callPackage ./libc++ { stdenv = pkgs.clangStdenv; };
+
+    libcxxabi = callPackage ./libc++abi { stdenv = pkgs.clangStdenv; };
+
+    #openmp = callPackage ./openmp {};
+  };
+in self
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/dragonegg.nix b/nixpkgs/pkgs/development/compilers/llvm/3.5/dragonegg.nix
new file mode 100644
index 000000000000..d54ffd96382d
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/dragonegg.nix
@@ -0,0 +1,26 @@
+{stdenv, fetch, llvm, gmp, mpfr, libmpc, ncurses, zlib, version}:
+
+stdenv.mkDerivation rec {
+  name = "dragonegg-${version}";
+
+  src = fetch "dragonegg" "1va4wv2b1dj0dpzsksnpnd0jic52q7pqj79w3m9jwdb58h7104dw";
+
+  # The gcc the plugin will be built for (the same used building dragonegg)
+  GCC = "gcc";
+
+  buildInputs = [ llvm gmp mpfr libmpc ncurses zlib ];
+
+  installPhase = ''
+    mkdir -p $out/lib $out/share/doc/${name}
+    cp -d dragonegg.so $out/lib
+    cp README COPYING $out/share/doc/${name}
+  '';
+
+  meta = {
+    homepage = http://dragonegg.llvm.org/;
+    description = "gcc plugin that replaces gcc's optimizers and code generators by those in LLVM";
+    license = stdenv.lib.licenses.gpl2Plus;
+    maintainers = with stdenv.lib.maintainers; [viric];
+    platforms = with stdenv.lib.platforms; linux;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/fix-15974.patch b/nixpkgs/pkgs/development/compilers/llvm/3.5/fix-15974.patch
new file mode 100644
index 000000000000..446004cd9988
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/fix-15974.patch
@@ -0,0 +1,15 @@
+diff --git a/include/llvm/ADT/IntrusiveRefCntPtr.h b/include/llvm/ADT/IntrusiveRefCntPtr.h
+index f9df378..9d860ec 100644
+--- a/include/llvm/ADT/IntrusiveRefCntPtr.h
++++ b/include/llvm/ADT/IntrusiveRefCntPtr.h
+@@ -134,9 +134,9 @@ public:
+ //===----------------------------------------------------------------------===//
+   template <typename T>
+   class IntrusiveRefCntPtr {
++  public:
+     T* Obj;
+ 
+-  public:
+     typedef T element_type;
+ 
+     explicit IntrusiveRefCntPtr() : Obj(nullptr) {}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/libc++/darwin.patch b/nixpkgs/pkgs/development/compilers/llvm/3.5/libc++/darwin.patch
new file mode 100644
index 000000000000..bf83f169cfc3
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/libc++/darwin.patch
@@ -0,0 +1,30 @@
+diff -ru -x '*~' libcxx-3.4.2.src-orig/lib/CMakeLists.txt libcxx-3.4.2.src/lib/CMakeLists.txt
+--- libcxx-3.4.2.src-orig/lib/CMakeLists.txt	2013-11-15 18:18:57.000000000 +0100
++++ libcxx-3.4.2.src/lib/CMakeLists.txt	2014-09-24 14:04:01.000000000 +0200
+@@ -56,7 +56,7 @@
+       "-compatibility_version 1"
+       "-current_version ${LIBCXX_VERSION}"
+       "-install_name /usr/lib/libc++.1.dylib"
+-      "-Wl,-reexport_library,/usr/lib/libc++abi.dylib"
++      "-Wl,-reexport_library,${LIBCXX_LIBCXXABI_LIB_PATH}/libc++abi.dylib"
+       "-Wl,-unexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++unexp.exp"
+       "/usr/lib/libSystem.B.dylib")
+   else()
+@@ -64,14 +64,14 @@
+       list(FIND ${CMAKE_OSX_ARCHITECTURES} "armv7" OSX_HAS_ARMV7)
+       if (OSX_HAS_ARMV7)
+         set(OSX_RE_EXPORT_LINE
+-          "${CMAKE_OSX_SYSROOT}/usr/lib/libc++abi.dylib"
++          "${CMAKE_OSX_SYSROOT}${LIBCXX_LIBCXXABI_LIB_PATH}/libc++abi.dylib"
+           "-Wl,-reexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++sjlj-abi.exp")
+       else()
+         set(OSX_RE_EXPORT_LINE
+-          "-Wl,-reexport_library,${CMAKE_OSX_SYSROOT}/usr/lib/libc++abi.dylib")
++          "-Wl,-reexport_library,${CMAKE_OSX_SYSROOT}${LIBCXX_LIBCXXABI_LIB_PATH}/libc++abi.dylib")
+       endif()
+     else()
+-      set (OSX_RE_EXPORT_LINE "/usr/lib/libc++abi.dylib -Wl,-reexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++abi${LIBCXX_LIBCPPABI_VERSION}.exp")
++      set (OSX_RE_EXPORT_LINE "${LIBCXX_LIBCXXABI_LIB_PATH}/libc++abi.dylib -Wl,-reexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++abi${LIBCXX_LIBCPPABI_VERSION}.exp")
+     endif()
+ 
+     list(APPEND link_flags
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/libc++/default.nix b/nixpkgs/pkgs/development/compilers/llvm/3.5/libc++/default.nix
new file mode 100644
index 000000000000..6edd5e9798c7
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/libc++/default.nix
@@ -0,0 +1,53 @@
+{ lib, stdenv, fetchurl, cmake, libcxxabi, fixDarwinDylibNames }:
+
+let version = "3.5.2"; in
+
+stdenv.mkDerivation rec {
+  name = "libc++-${version}";
+
+  src = fetchurl {
+    url = "http://llvm.org/releases/${version}/libcxx-${version}.src.tar.xz";
+    sha256 = "0irnl54fwzh2hzn9x4jfvnfyq5kd0zn0iwbzdivgwhqzw6fjdwdv";
+  };
+
+  # instead of allowing libc++ to link with /usr/lib/libc++abi.dylib,
+  # force it to link with our copy
+  preConfigure = stdenv.lib.optionalString stdenv.isDarwin ''
+    substituteInPlace lib/CMakeLists.txt \
+      --replace 'OSX_RE_EXPORT_LINE "/usr/lib/libc++abi.dylib' \
+                'OSX_RE_EXPORT_LINE "${libcxxabi}/lib/libc++abi.dylib' \
+      --replace '"''${CMAKE_OSX_SYSROOT}/usr/lib/libc++abi.dylib"' \
+                '"${libcxxabi}/lib/libc++abi.dylib"'
+  '';
+
+  patches = [
+    ./darwin.patch
+    # glibc 2.26 fix
+    ./xlocale-glibc-2.26.patch
+  ];
+
+  buildInputs = [ cmake libcxxabi ] ++ lib.optional stdenv.isDarwin fixDarwinDylibNames;
+
+  cmakeFlags = [
+    "-DLIBCXX_LIBCXXABI_INCLUDE_PATHS=${libcxxabi}/include"
+    "-DLIBCXX_LIBCXXABI_LIB_PATH=${libcxxabi}/lib"
+    "-DLIBCXX_LIBCPPABI_VERSION=2"
+    "-DLIBCXX_CXX_ABI=libcxxabi"
+  ];
+
+  enableParallelBuilding = true;
+
+  linkCxxAbi = stdenv.isLinux;
+
+  setupHooks = [
+    ../../../../../build-support/setup-hooks/role.bash
+    ./setup-hook.sh
+  ];
+
+  meta = {
+    homepage = http://libcxx.llvm.org/;
+    description = "A new implementation of the C++ standard library, targeting C++11";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/libc++/setup-hook.sh b/nixpkgs/pkgs/development/compilers/llvm/3.5/libc++/setup-hook.sh
new file mode 100644
index 000000000000..6611259165ae
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/libc++/setup-hook.sh
@@ -0,0 +1,6 @@
+# See pkgs/build-support/setup-hooks/role.bash
+getHostRole
+
+linkCxxAbi="@linkCxxAbi@"
+export NIX_${role_pre}CXXSTDLIB_COMPILE+=" -isystem @out@/include/c++/v1"
+export NIX_${role_pre}CXXSTDLIB_LINK=" -stdlib=libc++${linkCxxAbi:+" -lc++abi"}"
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/libc++/xlocale-glibc-2.26.patch b/nixpkgs/pkgs/development/compilers/llvm/3.5/libc++/xlocale-glibc-2.26.patch
new file mode 100644
index 000000000000..250bb49fc231
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/libc++/xlocale-glibc-2.26.patch
@@ -0,0 +1,17 @@
+diff --git a/include/__locale b/include/__locale
+index 3daa1f1..cb8e151 100644
+--- a/include/__locale
++++ b/include/__locale
+@@ -29,10 +29,10 @@
+ # if __ANDROID_API__ <= 20
+ #  include <support/android/locale_bionic.h>
+ # endif
+-#elif (defined(__GLIBC__) || defined(__APPLE__)      || defined(__FreeBSD__) \
++#elif (defined(__APPLE__)      || defined(__FreeBSD__) \
+     || defined(__sun__)   || defined(__EMSCRIPTEN__) || defined(__IBMCPP__))
+ # include <xlocale.h>
+-#endif // __GLIBC__ || __APPLE__ || __FreeBSD__ || __sun__ || __EMSCRIPTEN__ || __IBMCPP__
++#endif // __APPLE__ || __FreeBSD__ || __sun__ || __EMSCRIPTEN__ || __IBMCPP__
+ 
+ #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+ #pragma GCC system_header
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/libc++abi/default.nix b/nixpkgs/pkgs/development/compilers/llvm/3.5/libc++abi/default.nix
new file mode 100644
index 000000000000..268f2702a234
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/libc++abi/default.nix
@@ -0,0 +1,59 @@
+{ stdenv, cmake, fetchurl, libcxx, libunwind, llvm }:
+
+let
+  version = "3.5.2";
+  cmakeLists = fetchurl {
+    name   = "CMakeLists.txt";
+    url    = "http://llvm.org/svn/llvm-project/libcxxabi/trunk/CMakeLists.txt?p=217324";
+    sha256 = "10idgcbs4pcx6mjsbq1vjm8hzqqdk2p7k86cw9f473jmfyfwgf5j";
+  };
+in stdenv.mkDerivation {
+  name = "libc++abi-${version}";
+
+  src = fetchurl {
+    url    = "http://llvm.org/releases/${version}/libcxxabi-${version}.src.tar.xz";
+    sha256 = "1c6rv0zx0na1w4hdmdfq2f6nj7limb7d1krrknwajxxkcn4yws92";
+  };
+
+  buildInputs = [ cmake ] ++ stdenv.lib.optional (!stdenv.isDarwin) libunwind;
+
+  postUnpack = ''
+    unpackFile ${libcxx.src}
+    unpackFile ${llvm.src}
+    echo cp ${cmakeLists} libcxxabi-*/CMakeLists.txt
+    cp ${cmakeLists} libcxxabi-*/CMakeLists.txt
+    export NIX_CFLAGS_COMPILE+=" -I$PWD/include"
+    export cmakeFlags="-DLLVM_PATH=$PWD/$(ls -d llvm-*) -DLIBCXXABI_LIBCXX_INCLUDES=$PWD/$(ls -d libcxx-*)/include"
+  '' + stdenv.lib.optionalString stdenv.isDarwin ''
+    export TRIPLE=x86_64-apple-darwin
+  '';
+
+  installPhase = if stdenv.isDarwin
+    then ''
+      for file in lib/*; do
+        # this should be done in CMake, but having trouble figuring out
+        # the magic combination of necessary CMake variables
+        # if you fancy a try, take a look at
+        # http://www.cmake.org/Wiki/CMake_RPATH_handling
+        install_name_tool -id $out/$file $file
+      done
+      make install
+      install -d 755 $out/include
+      install -m 644 ../include/cxxabi.h $out/include
+    ''
+    else ''
+      install -d -m 755 $out/include $out/lib
+      install -m 644 lib/libc++abi.so.1.0 $out/lib
+      install -m 644 $src/include/cxxabi.h $out/include
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so.1
+    '';
+
+  meta = {
+    homepage = http://libcxxabi.llvm.org/;
+    description = "A new implementation of low level support for a standard C++ library";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    maintainers = with stdenv.lib.maintainers; [ vlstill ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/lld.nix b/nixpkgs/pkgs/development/compilers/llvm/3.5/lld.nix
new file mode 100644
index 000000000000..4a398bd96a05
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/lld.nix
@@ -0,0 +1,29 @@
+{ stdenv, fetch, cmake, llvm, ncurses, zlib, python, version }:
+
+stdenv.mkDerivation {
+  name = "lld-${version}";
+
+  src = fetch "lld" "1hpqawg1sc8mdqxqaxqmlzbrn69w1pkj8rxhjgqgmwra6c0xky89";
+
+  preUnpack = ''
+    # !!! Hopefully won't be needed for 3.5
+    unpackFile ${llvm.src}
+    export cmakeFlags="$cmakeFlags -DLLD_PATH_TO_LLVM_SOURCE="`ls -d $PWD/llvm-*`
+  '';
+
+  buildInputs = [ cmake ncurses zlib python ];
+
+  cmakeFlags = [
+    "-DCMAKE_CXX_FLAGS=-std=c++11"
+    "-DLLD_PATH_TO_LLVM_BUILD=${llvm}"
+  ];
+
+  enableParallelBuilding = true;
+
+  meta = {
+    description = "A set of modular code for creating linker tools";
+    homepage    = http://llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/lldb.nix b/nixpkgs/pkgs/development/compilers/llvm/3.5/lldb.nix
new file mode 100644
index 000000000000..a5161333b282
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/lldb.nix
@@ -0,0 +1,44 @@
+{ stdenv
+, fetch
+, cmake
+, zlib
+, ncurses
+, swig
+, which
+, libedit
+, llvm
+, clang
+, python
+, version
+}:
+
+stdenv.mkDerivation {
+  name = "lldb-${version}";
+
+  src = fetch "lldb" "0ffi9jn4k3yd0hvxs1v4n710x8siq21lb49v3351d7j5qinrpgi7";
+
+  patchPhase = ''
+    sed -i 's|/usr/bin/env||' \
+      scripts/Python/finish-swig-Python-LLDB.sh \
+      scripts/Python/build-swig-Python.sh
+  '';
+
+  buildInputs = [ cmake python which swig ncurses zlib libedit ];
+
+  cmakeFlags = [
+    "-DCMAKE_CXX_FLAGS=-std=c++11"
+    "-DLLDB_PATH_TO_LLVM_BUILD=${llvm}"
+    "-DLLDB_PATH_TO_CLANG_BUILD=${clang}"
+    "-DLLDB_DISABLE_LIBEDIT=1" # https://llvm.org/bugs/show_bug.cgi?id=28898
+  ];
+
+  enableParallelBuilding = true;
+
+  meta = {
+    description = "A next-generation high-performance debugger";
+    homepage    = http://llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    platforms   = stdenv.lib.platforms.all;
+    broken = true;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/llvm-separate-build.patch b/nixpkgs/pkgs/development/compilers/llvm/3.5/llvm-separate-build.patch
new file mode 100644
index 000000000000..abfc11513cdc
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/llvm-separate-build.patch
@@ -0,0 +1,12 @@
+diff -Naur llvm-3.4-orig/cmake/modules/TableGen.cmake llvm-3.4/cmake/modules/TableGen.cmake
+--- llvm-3.4-orig/cmake/modules/TableGen.cmake	2013-10-06 21:00:07.000000000 -0400
++++ llvm-3.4/cmake/modules/TableGen.cmake	2014-01-20 13:06:55.273022149 -0500
+@@ -78,8 +78,6 @@
+ endif()
+ 
+ macro(add_tablegen target project)
+-  set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${LLVM_TOOLS_BINARY_DIR})
+-
+   set(${target}_OLD_LLVM_LINK_COMPONENTS ${LLVM_LINK_COMPONENTS})
+   set(LLVM_LINK_COMPONENTS ${LLVM_LINK_COMPONENTS} TableGen)
+   add_llvm_utility(${target} ${ARGN})
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/llvm.nix b/nixpkgs/pkgs/development/compilers/llvm/3.5/llvm.nix
new file mode 100644
index 000000000000..2645469767ad
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/llvm.nix
@@ -0,0 +1,98 @@
+{ stdenv
+, fetch
+, fetchpatch
+, perl
+, groff
+, cmake
+, python
+, libffi
+, libbfd
+, libxml2
+, valgrind
+, ncurses
+, version
+, zlib
+, compiler-rt_src
+, debugVersion ? false
+, enableSharedLibraries ? !stdenv.isDarwin
+}:
+
+let
+  src = fetch "llvm" "0xf5q17kkxsrm2gsi93h4pwlv663kji73r2g4asb97klsmb626a4";
+in stdenv.mkDerivation rec {
+  name = "llvm-${version}";
+
+  unpackPhase = ''
+    unpackFile ${src}
+    mv llvm-${version}.src llvm
+    sourceRoot=$PWD/llvm
+    unpackFile ${compiler-rt_src}
+    mv compiler-rt-* $sourceRoot/projects/compiler-rt
+  '';
+
+  buildInputs = [ perl groff cmake libxml2 python libffi ] ++ stdenv.lib.optional stdenv.isLinux valgrind;
+
+  propagatedBuildInputs = [ ncurses zlib ];
+
+  prePatch = ''
+    substituteInPlace CMakeLists.txt \
+      --replace 'set(CMAKE_INSTALL_NAME_DIR "@rpath")' "set(CMAKE_INSTALL_NAME_DIR "$out/lib")" \
+      --replace 'set(CMAKE_INSTALL_RPATH "@executable_path/../lib")' ""
+  '';
+
+  postPatch = stdenv.lib.optionalString (stdenv ? glibc) ''
+    (
+      cd projects/compiler-rt
+      patch -p1 < ${
+        fetchpatch {
+          name = "sigaltstack.patch"; # for glibc-2.26
+          url = https://github.com/llvm-mirror/compiler-rt/commit/8a5e425a68d.diff;
+          sha256 = "0h4y5vl74qaa7dl54b1fcyqalvlpd8zban2d1jxfkxpzyi7m8ifi";
+        }
+      }
+
+      sed -i "s,#include <pthread.h>,&\n#include <signal.h>,g" \
+        lib/asan/asan_linux.cc
+    )
+  '';
+
+  # hacky fix: created binaries need to be run before installation
+  preBuild = ''
+    mkdir -p $out/
+    ln -sv $PWD/lib $out
+  '';
+
+  cmakeFlags = with stdenv; [
+    "-DCMAKE_BUILD_TYPE=${if debugVersion then "Debug" else "Release"}"
+    "-DLLVM_BUILD_TESTS=ON"
+    "-DLLVM_ENABLE_FFI=ON"
+    "-DLLVM_REQUIRES_RTTI=1"
+  ] ++ stdenv.lib.optional enableSharedLibraries
+    "-DBUILD_SHARED_LIBS=ON"
+    ++ stdenv.lib.optional (!isDarwin)
+    "-DLLVM_BINUTILS_INCDIR=${libbfd.dev}/include"
+    ++ stdenv.lib.optionals ( isDarwin) [
+    "-DCMAKE_CXX_FLAGS=-stdlib=libc++"
+    "-DCAN_TARGET_i386=false"
+  ];
+
+  patches = [ ./fix-15974.patch ] ++
+    stdenv.lib.optionals (!stdenv.isDarwin) [../fix-llvm-config.patch ];
+
+  postBuild = ''
+    rm -fR $out
+  '';
+
+  enableParallelBuilding = true;
+
+  passthru.src = src;
+
+  meta = {
+    description = "Collection of modular and reusable compiler and toolchain technologies";
+    homepage    = http://llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    maintainers = with stdenv.lib.maintainers; [ lovek323 raskin ];
+    platforms = [ "i686-linux" "x86_64-linux" "x86_64-darwin" "armv7l-linux"];
+  };
+}
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/polly-separate-build.patch b/nixpkgs/pkgs/development/compilers/llvm/3.5/polly-separate-build.patch
new file mode 100644
index 000000000000..618dd4dc3b12
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/polly-separate-build.patch
@@ -0,0 +1,12 @@
+diff -Naur polly-3.4-orig/CMakeLists.txt polly-3.4/CMakeLists.txt
+--- polly-3.4-orig/CMakeLists.txt	2013-11-21 06:51:46.000000000 -0500
++++ polly-3.4/CMakeLists.txt	2014-01-20 18:49:34.907919933 -0500
+@@ -53,7 +53,7 @@
+   execute_process(COMMAND "${LLVM_INSTALL_ROOT}/bin/llvm-config" --cxxflags
+                   OUTPUT_VARIABLE LLVM_CXX_FLAGS
+                   OUTPUT_STRIP_TRAILING_WHITESPACE)
+-  set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} ${LLVM_CXX_FLAGS})
++  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${LLVM_CXX_FLAGS}")
+ endif(NOT DEFINED LLVM_MAIN_SRC_DIR)
+ 
+ set(POLLY_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.5/polly.nix b/nixpkgs/pkgs/development/compilers/llvm/3.5/polly.nix
new file mode 100644
index 000000000000..bacf4d30556b
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.5/polly.nix
@@ -0,0 +1,25 @@
+{ stdenv, fetch, cmake, isl, python, gmp, llvm, version }:
+
+stdenv.mkDerivation {
+  name = "polly-${version}";
+
+  src =  fetch "polly" "1s6v54czmgq626an4yk2k34lrzkwmz1bjrbiafh7j23yc2w4nalx";
+
+  patches = [ ./polly-separate-build.patch ];
+
+  buildInputs = [ cmake isl python gmp ];
+
+  cmakeFlags = [
+    "-DCMAKE_CXX_FLAGS=-std=c++11"
+    "-DLLVM_INSTALL_ROOT=${llvm}"
+  ];
+
+  enableParallelBuilding = true;
+
+  meta = {
+    description = "A polyhedral optimizer for llvm";
+    homepage    = http://llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.7/clang/default.nix b/nixpkgs/pkgs/development/compilers/llvm/3.7/clang/default.nix
new file mode 100644
index 000000000000..4ccd00af6846
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.7/clang/default.nix
@@ -0,0 +1,60 @@
+{ stdenv, fetch, cmake, libxml2, llvm, version, clang-tools-extra_src }:
+
+let
+  gcc = if stdenv.cc.isGNU then stdenv.cc.cc else stdenv.cc.cc.gcc;
+  self = stdenv.mkDerivation {
+    name = "clang-${version}";
+
+    unpackPhase = ''
+      unpackFile ${fetch "cfe" "0x065d0w9b51xvdjxwfzjxng0gzpbx45fgiaxpap45ragi61dqjn"}
+      mv cfe-${version}.src clang
+      sourceRoot=$PWD/clang
+      unpackFile ${clang-tools-extra_src}
+      mv clang-tools-extra-* $sourceRoot/tools/extra
+    '';
+
+    buildInputs = [ cmake libxml2 llvm ];
+
+    cmakeFlags = [
+      "-DCMAKE_CXX_FLAGS=-std=c++11"
+    ] ++
+    # Maybe with compiler-rt this won't be needed?
+    (stdenv.lib.optional stdenv.isLinux "-DGCC_INSTALL_PREFIX=${gcc}") ++
+    (stdenv.lib.optional (stdenv.cc.libc != null) "-DC_INCLUDE_DIRS=${stdenv.cc.libc}/include");
+
+    patches = [ ./purity.patch ];
+
+    postPatch = ''
+      sed -i -e 's/Args.hasArg(options::OPT_nostdlibinc)/true/' lib/Driver/Tools.cpp
+      sed -i -e 's/DriverArgs.hasArg(options::OPT_nostdlibinc)/true/' lib/Driver/ToolChains.cpp
+    '';
+
+    # Clang expects to find LLVMgold in its own prefix
+    # Clang expects to find sanitizer libraries in its own prefix
+    postInstall = ''
+      if [ -e ${llvm}/lib/LLVMgold.so ]; then
+        ln -sv ${llvm}/lib/LLVMgold.so $out/lib
+      fi
+
+      ln -sv ${llvm}/lib/clang/${version}/lib $out/lib/clang/${version}/
+      ln -sv $out/bin/clang $out/bin/cpp
+    '';
+
+    enableParallelBuilding = true;
+
+    passthru = {
+      lib = self; # compatibility with gcc, so that `stdenv.cc.cc.lib` works on both
+      isClang = true;
+      inherit llvm;
+    } // stdenv.lib.optionalAttrs stdenv.isLinux {
+      inherit gcc;
+    };
+
+    meta = {
+      description = "A c, c++, objective-c, and objective-c++ frontend for the llvm compiler";
+      homepage    = http://llvm.org/;
+      license     = stdenv.lib.licenses.ncsa;
+      platforms   = stdenv.lib.platforms.all;
+    };
+  };
+in self
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.7/clang/purity.patch b/nixpkgs/pkgs/development/compilers/llvm/3.7/clang/purity.patch
new file mode 100644
index 000000000000..ee73b26eb5ce
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.7/clang/purity.patch
@@ -0,0 +1,17 @@
+--- a/lib/Driver/Tools.cpp	2015-07-31 00:47:41.000000000 +0200
++++ b/lib/Driver/Tools.cpp	2015-09-11 21:30:50.057895565 +0200
+@@ -8150,15 +8150,6 @@
+     CmdArgs.push_back("-shared");
+   }
+ 
+-  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
+-      Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
+-      (!Args.hasArg(options::OPT_static) &&
+-       !Args.hasArg(options::OPT_shared))) {
+-    CmdArgs.push_back("-dynamic-linker");
+-    CmdArgs.push_back(Args.MakeArgString(
+-        D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
+-  }
+-
+   CmdArgs.push_back("-o");
+   CmdArgs.push_back(Output.getFilename());
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.7/default.nix b/nixpkgs/pkgs/development/compilers/llvm/3.7/default.nix
new file mode 100644
index 000000000000..3c557711449f
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.7/default.nix
@@ -0,0 +1,59 @@
+{ newScope, stdenv, libstdcxxHook, isl, fetchurl
+, overrideCC, wrapCCWith
+, buildLlvmTools # tools, but from the previous stage, for cross
+, targetLlvmLibraries # libraries, but from the next stage, for cross
+}:
+
+let
+  version = "3.7.1";
+
+  fetch = fetch_v version;
+  fetch_v = ver: name: sha256: fetchurl {
+    url = "https://releases.llvm.org/${ver}/${name}-${ver}.src.tar.xz";
+    inherit sha256;
+  };
+
+  compiler-rt_src = fetch "compiler-rt" "10c1mz2q4bdq9bqfgr3dirc6hz1h3sq8573srd5q5lr7m7j6jiwx";
+  clang-tools-extra_src = fetch "clang-tools-extra" "0sxw2l3q5msbrwxv1ck72arggdw6n5ysi929gi69ikniranfv4aa";
+
+  tools = stdenv.lib.makeExtensible (tools: let
+    callPackage = newScope (tools // { inherit stdenv isl version fetch; });
+  in {
+    llvm = callPackage ./llvm.nix {
+      inherit compiler-rt_src;
+      inherit (targetLlvmLibraries) libcxxabi;
+    };
+
+    clang-unwrapped = callPackage ./clang {
+      inherit clang-tools-extra_src;
+    };
+
+    clang = if stdenv.cc.isGNU then tools.libstdcxxClang else tools.libcxxClang;
+
+    libstdcxxClang = wrapCCWith {
+      cc = tools.clang-unwrapped;
+      extraPackages = [ libstdcxxHook ];
+    };
+
+    libcxxClang = wrapCCWith {
+      cc = tools.clang-unwrapped;
+      extraPackages = [ targetLlvmLibraries.libcxx targetLlvmLibraries.libcxxabi ];
+    };
+
+    lldb = callPackage ./lldb.nix {};
+  });
+
+  libraries = stdenv.lib.makeExtensible (libraries: let
+    callPackage = newScope (libraries // buildLlvmTools // { inherit stdenv isl version fetch; });
+  in {
+
+    stdenv = overrideCC stdenv buildLlvmTools.clang;
+
+    libcxxStdenv = overrideCC stdenv buildLlvmTools.libcxxClang;
+
+    libcxx = callPackage ./libc++ {};
+
+    libcxxabi = callPackage ./libc++abi.nix {};
+  });
+
+in { inherit tools libraries; } // libraries // tools
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/darwin.patch b/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/darwin.patch
new file mode 100644
index 000000000000..bf83f169cfc3
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/darwin.patch
@@ -0,0 +1,30 @@
+diff -ru -x '*~' libcxx-3.4.2.src-orig/lib/CMakeLists.txt libcxx-3.4.2.src/lib/CMakeLists.txt
+--- libcxx-3.4.2.src-orig/lib/CMakeLists.txt	2013-11-15 18:18:57.000000000 +0100
++++ libcxx-3.4.2.src/lib/CMakeLists.txt	2014-09-24 14:04:01.000000000 +0200
+@@ -56,7 +56,7 @@
+       "-compatibility_version 1"
+       "-current_version ${LIBCXX_VERSION}"
+       "-install_name /usr/lib/libc++.1.dylib"
+-      "-Wl,-reexport_library,/usr/lib/libc++abi.dylib"
++      "-Wl,-reexport_library,${LIBCXX_LIBCXXABI_LIB_PATH}/libc++abi.dylib"
+       "-Wl,-unexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++unexp.exp"
+       "/usr/lib/libSystem.B.dylib")
+   else()
+@@ -64,14 +64,14 @@
+       list(FIND ${CMAKE_OSX_ARCHITECTURES} "armv7" OSX_HAS_ARMV7)
+       if (OSX_HAS_ARMV7)
+         set(OSX_RE_EXPORT_LINE
+-          "${CMAKE_OSX_SYSROOT}/usr/lib/libc++abi.dylib"
++          "${CMAKE_OSX_SYSROOT}${LIBCXX_LIBCXXABI_LIB_PATH}/libc++abi.dylib"
+           "-Wl,-reexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++sjlj-abi.exp")
+       else()
+         set(OSX_RE_EXPORT_LINE
+-          "-Wl,-reexport_library,${CMAKE_OSX_SYSROOT}/usr/lib/libc++abi.dylib")
++          "-Wl,-reexport_library,${CMAKE_OSX_SYSROOT}${LIBCXX_LIBCXXABI_LIB_PATH}/libc++abi.dylib")
+       endif()
+     else()
+-      set (OSX_RE_EXPORT_LINE "/usr/lib/libc++abi.dylib -Wl,-reexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++abi${LIBCXX_LIBCPPABI_VERSION}.exp")
++      set (OSX_RE_EXPORT_LINE "${LIBCXX_LIBCXXABI_LIB_PATH}/libc++abi.dylib -Wl,-reexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++abi${LIBCXX_LIBCPPABI_VERSION}.exp")
+     endif()
+ 
+     list(APPEND link_flags
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/default.nix b/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/default.nix
new file mode 100644
index 000000000000..462e35a483f4
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/default.nix
@@ -0,0 +1,47 @@
+{ lib, stdenv, fetch, cmake, libcxxabi, fixDarwinDylibNames, version }:
+
+stdenv.mkDerivation rec {
+  name = "libc++-${version}";
+
+  src = fetch "libcxx" "0i7iyzk024krda5spfpfi8jksh83yp3bxqkal0xp76ffi11bszrm";
+
+  postUnpack = ''
+    unpackFile ${libcxxabi.src}
+  '';
+
+  preConfigure = ''
+    # Get headers from the cxxabi source so we can see private headers not installed by the cxxabi package
+    cmakeFlagsArray=($cmakeFlagsArray -DLIBCXX_CXX_ABI_INCLUDE_PATHS="$NIX_BUILD_TOP/libcxxabi-${version}.src/include")
+  '';
+
+  patches = [
+    ./darwin.patch
+    ./r242056.patch
+    # glibc 2.26 fix
+    ./xlocale-glibc-2.26.patch
+  ];
+
+  buildInputs = [ cmake libcxxabi ] ++ lib.optional stdenv.isDarwin fixDarwinDylibNames;
+
+  cmakeFlags = [
+    "-DLIBCXX_LIBCXXABI_LIB_PATH=${libcxxabi}/lib"
+    "-DLIBCXX_LIBCPPABI_VERSION=2"
+    "-DLIBCXX_CXX_ABI=libcxxabi"
+  ];
+
+  enableParallelBuilding = true;
+
+  linkCxxAbi = stdenv.isLinux;
+
+  setupHooks = [
+    ../../../../../build-support/setup-hooks/role.bash
+    ./setup-hook.sh
+  ];
+
+  meta = {
+    homepage = http://libcxx.llvm.org/;
+    description = "A new implementation of the C++ standard library, targeting C++11";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/r242056.patch b/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/r242056.patch
new file mode 100644
index 000000000000..96245e76653a
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/r242056.patch
@@ -0,0 +1,16 @@
+--- a/include/string	2015/07/13 20:04:56	242056
++++ b/include/string	2015/07/18 20:40:46	242623
+@@ -1936,7 +1936,12 @@
+ template <class _CharT, class _Traits, class _Allocator>
+ inline _LIBCPP_INLINE_VISIBILITY
+ basic_string<_CharT, _Traits, _Allocator>::basic_string(const allocator_type& __a)
+-    : __r_(__a)
++#if _LIBCPP_STD_VER <= 14
++        _NOEXCEPT_(is_nothrow_copy_constructible<allocator_type>::value)
++#else
++        _NOEXCEPT
++#endif
++: __r_(__a)
+ {
+ #if _LIBCPP_DEBUG_LEVEL >= 2
+     __get_db()->__insert_c(this);
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/setup-hook.sh b/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/setup-hook.sh
new file mode 100644
index 000000000000..6611259165ae
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/setup-hook.sh
@@ -0,0 +1,6 @@
+# See pkgs/build-support/setup-hooks/role.bash
+getHostRole
+
+linkCxxAbi="@linkCxxAbi@"
+export NIX_${role_pre}CXXSTDLIB_COMPILE+=" -isystem @out@/include/c++/v1"
+export NIX_${role_pre}CXXSTDLIB_LINK=" -stdlib=libc++${linkCxxAbi:+" -lc++abi"}"
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/xlocale-glibc-2.26.patch b/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/xlocale-glibc-2.26.patch
new file mode 100644
index 000000000000..5ee8f6b82305
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++/xlocale-glibc-2.26.patch
@@ -0,0 +1,17 @@
+diff --git a/include/__locale b/include/__locale
+index 1989558..1e42905 100644
+--- a/include/__locale
++++ b/include/__locale
+@@ -34,10 +34,10 @@
+ # include <support/solaris/xlocale.h>
+ #elif defined(_NEWLIB_VERSION)
+ # include <support/newlib/xlocale.h>
+-#elif (defined(__GLIBC__) || defined(__APPLE__)      || defined(__FreeBSD__) \
++#elif (defined(__APPLE__)      || defined(__FreeBSD__) \
+     || defined(__EMSCRIPTEN__) || defined(__IBMCPP__))
+ # include <xlocale.h>
+-#endif // __GLIBC__ || __APPLE__ || __FreeBSD__ || __sun__ || __EMSCRIPTEN__ || __IBMCPP__
++#endif // __APPLE__ || __FreeBSD__ || __sun__ || __EMSCRIPTEN__ || __IBMCPP__
+ 
+ #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+ #pragma GCC system_header
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++abi.nix b/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++abi.nix
new file mode 100644
index 000000000000..2c79d7b3b1b5
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.7/libc++abi.nix
@@ -0,0 +1,61 @@
+{ stdenv, cmake, fetch, fetchpatch, libcxx, libunwind, llvm, version }:
+
+let
+  # Newer LLVMs (3.8 onwards) have changed how some basic C++ stuff works, which breaks builds of this older version
+  llvm38-and-above = fetchpatch {
+    url    = "https://trac.macports.org/raw-attachment/ticket/50304/0005-string-Fix-exception-declaration.patch";
+    sha256 = "1lm38n7s0l5dbl7kp4i49pvzxz1mcvlr2vgsnj47agnwhhm63jvr";
+  };
+in stdenv.mkDerivation {
+  name = "libc++abi-${version}";
+
+  src = fetch "libcxxabi" "0ambfcmr2nh88hx000xb7yjm9lsqjjz49w5mlf6dlxzmj3nslzx4";
+
+  nativeBuildInputs = [ cmake ];
+  buildInputs = stdenv.lib.optional (!stdenv.isDarwin && !stdenv.isFreeBSD) libunwind;
+
+  postUnpack = ''
+    unpackFile ${libcxx.src}
+    unpackFile ${llvm.src}
+    export NIX_CFLAGS_COMPILE+=" -I$PWD/include"
+    export cmakeFlags="-DLLVM_PATH=$PWD/$(ls -d llvm-*) -DLIBCXXABI_LIBCXX_INCLUDES=$PWD/$(ls -d libcxx-*)/include"
+  '' + stdenv.lib.optionalString stdenv.isDarwin ''
+    export TRIPLE=x86_64-apple-darwin
+  '';
+
+  # I can't use patches directly because this is actually a patch for libc++'s source, which we manually extract
+  # into the libc++abi build environment above.
+  prePatch = ''(
+    cd ../libcxx-*
+    patch -p1 < ${llvm38-and-above}
+  )'';
+
+  installPhase = if stdenv.isDarwin
+    then ''
+      for file in lib/*.dylib; do
+        # this should be done in CMake, but having trouble figuring out
+        # the magic combination of necessary CMake variables
+        # if you fancy a try, take a look at
+        # http://www.cmake.org/Wiki/CMake_RPATH_handling
+        install_name_tool -id $out/$file $file
+      done
+      make install
+      install -d 755 $out/include
+      install -m 644 ../include/*.h $out/include
+    ''
+    else ''
+      install -d -m 755 $out/include $out/lib
+      install -m 644 lib/libc++abi.so.1.0 $out/lib
+      install -m 644 ../include/cxxabi.h $out/include
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so.1
+    '';
+
+  meta = {
+    homepage = http://libcxxabi.llvm.org/;
+    description = "A new implementation of low level support for a standard C++ library";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    maintainers = with stdenv.lib.maintainers; [ vlstill ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.7/lldb.nix b/nixpkgs/pkgs/development/compilers/llvm/3.7/lldb.nix
new file mode 100644
index 000000000000..294410f99869
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.7/lldb.nix
@@ -0,0 +1,49 @@
+{ stdenv
+, fetch
+, cmake
+, zlib
+, ncurses
+, swig
+, which
+, libedit
+, llvm
+, clang-unwrapped
+, python2
+, version
+}:
+
+stdenv.mkDerivation {
+  name = "lldb-${version}";
+
+  src = fetch "lldb" "008fdbyza13ym3v0xpans4z4azw4y16hcbgrrnc4rx2mxwaw62ws";
+
+  patchPhase = ''
+    sed -i 's|/usr/bin/env||' \
+      scripts/Python/finish-swig-Python-LLDB.sh \
+      scripts/Python/build-swig-Python.sh
+  '';
+
+  buildInputs = [ cmake python2 which swig ncurses zlib libedit ];
+
+  preConfigure = ''
+    export CXXFLAGS="-pthread"
+    export LDFLAGS="-ldl"
+  '';
+
+  cmakeFlags = [
+    "-DLLDB_PATH_TO_LLVM_BUILD=${llvm}"
+    "-DLLDB_PATH_TO_CLANG_BUILD=${clang-unwrapped}"
+    "-DPYTHON_VERSION_MAJOR=2"
+    "-DPYTHON_VERSION_MINOR=7"
+    "-DLLDB_DISABLE_LIBEDIT=1" # https://llvm.org/bugs/show_bug.cgi?id=28898
+  ];
+
+  enableParallelBuilding = true;
+
+  meta = {
+    description = "A next-generation high-performance debugger";
+    homepage    = http://llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.7/llvm.nix b/nixpkgs/pkgs/development/compilers/llvm/3.7/llvm.nix
new file mode 100644
index 000000000000..a6fd18f94d68
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.7/llvm.nix
@@ -0,0 +1,105 @@
+{ stdenv
+, fetch
+, fetchpatch
+, perl
+, groff
+, cmake
+, python2
+, libffi
+, libbfd
+, libxml2
+, ncurses
+, version
+, zlib
+, compiler-rt_src
+, libcxxabi
+, debugVersion ? false
+, enableSharedLibraries ? !stdenv.isDarwin
+}:
+
+let
+  src = fetch "llvm" "1masakdp9g2dan1yrazg7md5am2vacbkb3nahb3dchpc1knr8xxy";
+in stdenv.mkDerivation rec {
+  name = "llvm-${version}";
+
+  unpackPhase = ''
+    unpackFile ${src}
+    mv llvm-${version}.src llvm
+    sourceRoot=$PWD/llvm
+    unpackFile ${compiler-rt_src}
+    mv compiler-rt-* $sourceRoot/projects/compiler-rt
+  '';
+
+  buildInputs = [ perl groff cmake libxml2 python2 libffi ]
+    ++ stdenv.lib.optional stdenv.isDarwin libcxxabi;
+
+  propagatedBuildInputs = [ ncurses zlib ];
+
+  # The goal here is to disable LLVM bindings (currently go and ocaml) regardless
+  # of whether the impure CMake search sheananigans find the compilers in global
+  # paths. This mostly exists because sandbox builds don't work very well on Darwin
+  # and sometimes you get weird behavior if CMake finds go in your system path.
+  # This would be far prettier if there were a CMake option to just disable bindings
+  # but from what I can tell, there isn't such a thing. The file in question only
+  # contains `if(WIN32)` conditions to check whether to disable bindings, so making
+  # those always succeed has the net effect of disabling all bindings.
+  prePatch = ''
+    substituteInPlace cmake/config-ix.cmake --replace "if(WIN32)" "if(1)"
+  ''
+  + stdenv.lib.optionalString (stdenv ? glibc) ''
+    (
+      cd projects/compiler-rt
+      patch -p1 < ${
+        fetchpatch {
+          name = "sigaltstack.patch"; # for glibc-2.26
+          url = https://github.com/llvm-mirror/compiler-rt/commit/8a5e425a68d.diff;
+          sha256 = "0h4y5vl74qaa7dl54b1fcyqalvlpd8zban2d1jxfkxpzyi7m8ifi";
+        }
+      }
+    )
+  '';
+
+  # hacky fix: created binaries need to be run before installation
+  preBuild = ''
+    mkdir -p $out/
+    ln -sv $PWD/lib $out
+  '';
+
+  patches = stdenv.lib.optionals (!stdenv.isDarwin) [
+    # llvm-config --libfiles returns (non-existing) static libs
+    ../fix-llvm-config.patch
+  ];
+
+  cmakeFlags = with stdenv; [
+    "-DCMAKE_BUILD_TYPE=${if debugVersion then "Debug" else "Release"}"
+    "-DLLVM_INSTALL_UTILS=ON"  # Needed by rustc
+    "-DLLVM_BUILD_TESTS=ON"
+    "-DLLVM_ENABLE_FFI=ON"
+    "-DLLVM_ENABLE_RTTI=ON"
+  ] ++ stdenv.lib.optional enableSharedLibraries
+    "-DBUILD_SHARED_LIBS=ON"
+    ++ stdenv.lib.optional (!isDarwin)
+    "-DLLVM_BINUTILS_INCDIR=${libbfd.dev}/include"
+    ++ stdenv.lib.optionals ( isDarwin) [
+    "-DLLVM_ENABLE_LIBCXX=ON"
+    "-DCAN_TARGET_i386=false"
+  ];
+
+  NIX_LDFLAGS = "-lpthread"; # no idea what's the problem
+
+  postBuild = ''
+    rm -fR $out
+  '';
+
+  enableParallelBuilding = true;
+
+  passthru.src = src;
+
+  meta = {
+    description = "Collection of modular and reusable compiler and toolchain technologies";
+    homepage    = http://llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    maintainers = with stdenv.lib.maintainers; [ lovek323 raskin ];
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.8/D17533-1.patch b/nixpkgs/pkgs/development/compilers/llvm/3.8/D17533-1.patch
new file mode 100644
index 000000000000..79ca953d6e5b
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.8/D17533-1.patch
@@ -0,0 +1,60 @@
+commit eb92f5a745014532b83abfba04602fce87ca8393
+Author: Chuang-Yu Cheng <cycheng@multicorewareinc.com>
+Date:   Fri Apr 8 12:04:32 2016 +0000
+
+    CXX_FAST_TLS calling convention: performance improvement for PPC64
+    
+    This is the same change on PPC64 as r255821 on AArch64. I have even borrowed
+    his commit message.
+    
+    The access function has a short entry and a short exit, the initialization
+    block is only run the first time. To improve the performance, we want to
+    have a short frame at the entry and exit.
+    
+    We explicitly handle most of the CSRs via copies. Only the CSRs that are not
+    handled via copies will be in CSR_SaveList.
+    
+    Frame lowering and prologue/epilogue insertion will generate a short frame
+    in the entry and exit according to CSR_SaveList. The majority of the CSRs will
+    be handled by register allcoator. Register allocator will try to spill and
+    reload them in the initialization block.
+    
+    We add CSRsViaCopy, it will be explicitly handled during lowering.
+    
+    1> we first set FunctionLoweringInfo->SplitCSR if conditions are met (the target
+       supports it for the given machine function and the function has only return
+       exits). We also call TLI->initializeSplitCSR to perform initialization.
+    2> we call TLI->insertCopiesSplitCSR to insert copies from CSRsViaCopy to
+       virtual registers at beginning of the entry block and copies from virtual
+       registers to CSRsViaCopy at beginning of the exit blocks.
+    3> we also need to make sure the explicit copies will not be eliminated.
+    
+    Author: Tom Jablin (tjablin)
+    Reviewers: hfinkel kbarton cycheng
+    
+    http://reviews.llvm.org/D17533
+    
+    git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@265781 91177308-0d34-0410-b5e6-96231b3b80d8
+
+diff --git a/lib/CodeGen/TargetFrameLoweringImpl.cpp b/lib/CodeGen/TargetFrameLoweringImpl.cpp
+index 679ade1..0a0e079 100644
+--- a/lib/CodeGen/TargetFrameLoweringImpl.cpp
++++ b/lib/CodeGen/TargetFrameLoweringImpl.cpp
+@@ -63,12 +63,15 @@ void TargetFrameLowering::determineCalleeSaves(MachineFunction &MF,
+   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
+   const MCPhysReg *CSRegs = TRI.getCalleeSavedRegs(&MF);
+ 
++  // Resize before the early returns. Some backends expect that
++  // SavedRegs.size() == TRI.getNumRegs() after this call even if there are no
++  // saved registers.
++  SavedRegs.resize(TRI.getNumRegs());
++
+   // Early exit if there are no callee saved registers.
+   if (!CSRegs || CSRegs[0] == 0)
+     return;
+ 
+-  SavedRegs.resize(TRI.getNumRegs());
+-
+   // In Naked functions we aren't going to save any registers.
+   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
+     return;
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.8/clang/default.nix b/nixpkgs/pkgs/development/compilers/llvm/3.8/clang/default.nix
new file mode 100644
index 000000000000..cc25a41b0400
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.8/clang/default.nix
@@ -0,0 +1,78 @@
+{ stdenv, fetch, cmake, libxml2, llvm, version, clang-tools-extra_src, python }:
+
+let
+  gcc = if stdenv.cc.isGNU then stdenv.cc.cc else stdenv.cc.cc.gcc;
+  self = stdenv.mkDerivation {
+    name = "clang-${version}";
+
+    unpackPhase = ''
+      unpackFile ${fetch "cfe" "1prc72xmkgx8wrzmrr337776676nhsp1qd3mw2bvb22bzdnq7lsc"}
+      mv cfe-${version}.src clang
+      sourceRoot=$PWD/clang
+      unpackFile ${clang-tools-extra_src}
+      mv clang-tools-extra-* $sourceRoot/tools/extra
+    '';
+
+    nativeBuildInputs = [ cmake ];
+    buildInputs = [ libxml2 llvm python ];
+
+    cmakeFlags = [
+      "-DCMAKE_CXX_FLAGS=-std=c++11"
+    ] ++
+    # Maybe with compiler-rt this won't be needed?
+    (stdenv.lib.optional stdenv.isLinux "-DGCC_INSTALL_PREFIX=${gcc}") ++
+    (stdenv.lib.optional (stdenv.cc.libc != null) "-DC_INCLUDE_DIRS=${stdenv.cc.libc}/include");
+
+    patches = [ ./purity.patch ];
+
+    postPatch = ''
+      sed -i -e 's/Args.hasArg(options::OPT_nostdlibinc)/true/' lib/Driver/Tools.cpp
+      sed -i -e 's/DriverArgs.hasArg(options::OPT_nostdlibinc)/true/' lib/Driver/ToolChains.cpp
+    '' + stdenv.lib.optionalString stdenv.hostPlatform.isMusl ''
+      sed -i -e 's/lgcc_s/lgcc_eh/' lib/Driver/Tools.cpp
+    '';
+
+    outputs = [ "out" "lib" "python" ];
+
+    # Clang expects to find LLVMgold in its own prefix
+    # Clang expects to find sanitizer libraries in its own prefix
+    postInstall = ''
+      if [ -e ${llvm}/lib/LLVMgold.so ]; then
+        ln -sv ${llvm}/lib/LLVMgold.so $out/lib
+      fi
+
+      ln -sv ${llvm}/lib/clang/${version}/lib $out/lib/clang/${version}/
+      ln -sv $out/bin/clang $out/bin/cpp
+
+      # Move libclang to 'lib' output
+      moveToOutput "lib/libclang.*" "$lib"
+      substituteInPlace $out/share/clang/cmake/ClangTargets-release.cmake \
+          --replace "\''${_IMPORT_PREFIX}/lib/libclang." "$lib/lib/libclang."
+
+      mkdir -p $python/bin $python/share/clang/
+      mv $out/bin/{git-clang-format,scan-view} $python/bin
+      if [ -e $out/bin/set-xcode-analyzer ]; then
+        mv $out/bin/set-xcode-analyzer $python/bin
+      fi
+      mv $out/share/clang/*.py $python/share/clang
+
+      rm $out/bin/c-index-test
+    '';
+
+    enableParallelBuilding = true;
+
+    passthru = {
+      isClang = true;
+      inherit llvm;
+    } // stdenv.lib.optionalAttrs stdenv.isLinux {
+      inherit gcc;
+    };
+
+    meta = {
+      description = "A c, c++, objective-c, and objective-c++ frontend for the llvm compiler";
+      homepage    = http://llvm.org/;
+      license     = stdenv.lib.licenses.ncsa;
+      platforms   = stdenv.lib.platforms.all;
+    };
+  };
+in self
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.8/clang/purity.patch b/nixpkgs/pkgs/development/compilers/llvm/3.8/clang/purity.patch
new file mode 100644
index 000000000000..2d1c68d865e6
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.8/clang/purity.patch
@@ -0,0 +1,17 @@
+--- a/lib/Driver/Tools.cpp	2016-02-12 15:51:41.000000000 -0700
++++ b/lib/Driver/Tools.cpp	2016-03-08 15:39:06.790111122 -0700
+@@ -8833,15 +8833,6 @@
+     CmdArgs.push_back("-shared");
+   }
+ 
+-  if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
+-      Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
+-      (!Args.hasArg(options::OPT_static) &&
+-       !Args.hasArg(options::OPT_shared))) {
+-    CmdArgs.push_back("-dynamic-linker");
+-    CmdArgs.push_back(Args.MakeArgString(
+-        D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
+-  }
+-
+   CmdArgs.push_back("-o");
+   CmdArgs.push_back(Output.getFilename());
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.8/default.nix b/nixpkgs/pkgs/development/compilers/llvm/3.8/default.nix
new file mode 100644
index 000000000000..a848c8b9252b
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.8/default.nix
@@ -0,0 +1,59 @@
+{ newScope, stdenv, libstdcxxHook, isl, fetchurl, overrideCC, wrapCCWith
+, buildLlvmTools # tools, but from the previous stage, for cross
+, targetLlvmLibraries # libraries, but from the next stage, for cross
+}:
+
+let
+  version = "3.8.1";
+
+  fetch = fetch_v version;
+  fetch_v = ver: name: sha256: fetchurl {
+    url = "https://releases.llvm.org/${ver}/${name}-${ver}.src.tar.xz";
+    inherit sha256;
+  };
+
+  compiler-rt_src = fetch "compiler-rt" "0p0y85c7izndbpg2l816z7z7558axq11d5pwkm4h11sdw7d13w0d";
+  clang-tools-extra_src = fetch "clang-tools-extra" "15n39r4ssphpaq4a0wzyjm7ilwxb0bch6nrapy8c5s8d49h5qjk6";
+
+  tools = stdenv.lib.makeExtensible (tools: let
+    callPackage = newScope (tools // { inherit stdenv isl version fetch; });
+ in {
+    llvm = callPackage ./llvm.nix {
+      inherit compiler-rt_src;
+    };
+
+    clang-unwrapped = callPackage ./clang {
+      inherit clang-tools-extra_src;
+    };
+
+    libclang = tools.clang-unwrapped.lib;
+
+    clang = if stdenv.cc.isGNU then tools.libstdcxxClang else tools.libcxxClang;
+
+    libstdcxxClang = wrapCCWith {
+      cc = tools.clang-unwrapped;
+      extraPackages = [ libstdcxxHook ];
+    };
+
+    libcxxClang = wrapCCWith {
+      cc = tools.clang-unwrapped;
+      extraPackages = [ targetLlvmLibraries.libcxx targetLlvmLibraries.libcxxabi ];
+    };
+
+    lldb = callPackage ./lldb.nix {};
+  });
+
+  libraries = stdenv.lib.makeExtensible (libraries: let
+    callPackage = newScope (libraries // buildLlvmTools // { inherit stdenv isl version fetch; });
+  in {
+
+    stdenv = overrideCC stdenv buildLlvmTools.clang;
+
+    libcxxStdenv = overrideCC stdenv buildLlvmTools.libcxxClang;
+
+    libcxx = callPackage ./libc++ {};
+
+    libcxxabi = callPackage ./libc++abi.nix {};
+  });
+
+in { inherit tools libraries; } // libraries // tools
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.8/fix-llvm-config.patch b/nixpkgs/pkgs/development/compilers/llvm/3.8/fix-llvm-config.patch
new file mode 100644
index 000000000000..6e56c67c8977
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.8/fix-llvm-config.patch
@@ -0,0 +1,11 @@
+--- llvm.org/utils/llvm-build/llvmbuild/main.py	2015-10-07 00:24:35.000000000 +0100
++++ llvm/utils/llvm-build/llvmbuild/main.py	2017-06-16 17:08:39.866586578 +0100
+@@ -413,7 +413,7 @@
+             if library_name is None:
+                 library_name_as_cstr = 'nullptr'
+             else:
+-                library_name_as_cstr = '"lib%s.a"' % library_name
++                library_name_as_cstr = '"lib%s.so"' % library_name
+             if is_installed:
+                 is_installed_as_cstr = 'true'
+             else:
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.8/libc++/darwin.patch b/nixpkgs/pkgs/development/compilers/llvm/3.8/libc++/darwin.patch
new file mode 100644
index 000000000000..6dd756f01cc2
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.8/libc++/darwin.patch
@@ -0,0 +1,39 @@
+--- libcxx-3.8.0.src.org/lib/CMakeLists.txt	2015-12-16 15:41:05.000000000 -0800
++++ libcxx-3.8.0.src/lib/CMakeLists.txt	2016-06-17 19:40:00.293394500 -0700
+@@ -94,30 +94,30 @@
+     add_definitions(-D__STRICT_ANSI__)
+     add_link_flags(
+       "-compatibility_version 1"
+       "-current_version 1"
+-      "-install_name /usr/lib/libc++.1.dylib"
+-      "-Wl,-reexport_library,/usr/lib/libc++abi.dylib"
++      "-install_name ${LIBCXX_LIBCXXABI_LIB_PATH}/libc++.1.dylib"
++      "-Wl,-reexport_library,${LIBCXX_LIBCXXABI_LIB_PATH}/libc++abi.dylib"
+       "-Wl,-unexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++unexp.exp"
+       "/usr/lib/libSystem.B.dylib")
+   else()
+     if ( ${CMAKE_OSX_SYSROOT} )
+       list(FIND ${CMAKE_OSX_ARCHITECTURES} "armv7" OSX_HAS_ARMV7)
+       if (OSX_HAS_ARMV7)
+         set(OSX_RE_EXPORT_LINE
+-          "${CMAKE_OSX_SYSROOT}/usr/lib/libc++abi.dylib"
++          "${CMAKE_OSX_SYSROOT}${LIBCXX_LIBCXXABI_LIB_PATH}/libc++abi.dylib"
+           "-Wl,-reexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++sjlj-abi.exp")
+       else()
+         set(OSX_RE_EXPORT_LINE
+-          "-Wl,-reexport_library,${CMAKE_OSX_SYSROOT}/usr/lib/libc++abi.dylib")
++          "-Wl,-reexport_library,${CMAKE_OSX_SYSROOT}${LIBCXX_LIBCXXABI_LIB_PATH}/libc++abi.dylib")
+       endif()
+     else()
+-      set(OSX_RE_EXPORT_LINE "/usr/lib/libc++abi.dylib -Wl,-reexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++abi${LIBCXX_LIBCPPABI_VERSION}.exp")
++      set(OSX_RE_EXPORT_LINE "${LIBCXX_LIBCXXABI_LIB_PATH}/libc++abi.dylib -Wl,-reexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++abi${LIBCXX_LIBCPPABI_VERSION}.exp")
+     endif()
+ 
+     add_link_flags(
+       "-compatibility_version 1"
+-      "-install_name /usr/lib/libc++.1.dylib"
++      "-install_name ${LIBCXX_LIBCXXABI_LIB_PATH}/libc++.1.dylib"
+       "-Wl,-unexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++unexp.exp"
+       "${OSX_RE_EXPORT_LINE}"
+       "-Wl,-force_symbols_not_weak_list,${CMAKE_CURRENT_SOURCE_DIR}/notweak.exp"
+       "-Wl,-force_symbols_weak_list,${CMAKE_CURRENT_SOURCE_DIR}/weak.exp")
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.8/libc++/default.nix b/nixpkgs/pkgs/development/compilers/llvm/3.8/libc++/default.nix
new file mode 100644
index 000000000000..5a0410302f2f
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.8/libc++/default.nix
@@ -0,0 +1,52 @@
+{ lib, stdenv, fetch, cmake, libcxxabi, fixDarwinDylibNames, version }:
+
+stdenv.mkDerivation rec {
+  name = "libc++-${version}";
+
+  src = fetch "libcxx" "1k7f9qk5bgwa02ksh6yr9hccwcbhmcdzl1fpbdw6s2c89iwg7mvp";
+
+  postUnpack = ''
+    unpackFile ${libcxxabi.src}
+  '';
+
+  preConfigure = ''
+    # Get headers from the cxxabi source so we can see private headers not installed by the cxxabi package
+    cmakeFlagsArray=($cmakeFlagsArray -DLIBCXX_CXX_ABI_INCLUDE_PATHS="$NIX_BUILD_TOP/libcxxabi-${version}.src/include")
+  '';
+
+  patches = [
+    # glibc 2.26 fix
+    ../../3.9/libc++/xlocale-glibc-2.26.patch
+  ]
+  ++ lib.optional stdenv.isDarwin ./darwin.patch
+  ++ stdenv.lib.optionals stdenv.hostPlatform.isMusl [
+    ../../libcxx-0001-musl-hacks.patch
+    ../../libcxx-max_align_t.patch
+  ];
+
+  nativeBuildInputs = [ cmake ];
+
+  buildInputs = [ libcxxabi ] ++ lib.optional stdenv.isDarwin fixDarwinDylibNames;
+
+  cmakeFlags = [
+    "-DLIBCXX_LIBCXXABI_LIB_PATH=${libcxxabi}/lib"
+    "-DLIBCXX_LIBCPPABI_VERSION=2"
+    "-DLIBCXX_CXX_ABI=libcxxabi"
+  ] ++ stdenv.lib.optional stdenv.hostPlatform.isMusl "-DLIBCXX_HAS_MUSL_LIBC=1";
+
+  enableParallelBuilding = true;
+
+  linkCxxAbi = stdenv.isLinux;
+
+  setupHooks = [
+    ../../../../../build-support/setup-hooks/role.bash
+    ./setup-hook.sh
+  ];
+
+  meta = {
+    homepage = http://libcxx.llvm.org/;
+    description = "A new implementation of the C++ standard library, targeting C++11";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.8/libc++/setup-hook.sh b/nixpkgs/pkgs/development/compilers/llvm/3.8/libc++/setup-hook.sh
new file mode 100644
index 000000000000..6611259165ae
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.8/libc++/setup-hook.sh
@@ -0,0 +1,6 @@
+# See pkgs/build-support/setup-hooks/role.bash
+getHostRole
+
+linkCxxAbi="@linkCxxAbi@"
+export NIX_${role_pre}CXXSTDLIB_COMPILE+=" -isystem @out@/include/c++/v1"
+export NIX_${role_pre}CXXSTDLIB_LINK=" -stdlib=libc++${linkCxxAbi:+" -lc++abi"}"
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.8/libc++abi.nix b/nixpkgs/pkgs/development/compilers/llvm/3.8/libc++abi.nix
new file mode 100644
index 000000000000..8b25681c2dbf
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.8/libc++abi.nix
@@ -0,0 +1,51 @@
+{ stdenv, cmake, fetch, libcxx, libunwind, llvm, version }:
+
+stdenv.mkDerivation {
+  name = "libc++abi-${version}";
+
+  src = fetch "libcxxabi" "1qfs2iis1i0ppv11jndc98cvd7s25pj46pq2sfyldmzswdxmzdg1";
+
+  nativeBuildInputs = [ cmake ];
+  buildInputs = stdenv.lib.optional (!stdenv.isDarwin && !stdenv.isFreeBSD) libunwind;
+
+  postUnpack = ''
+    unpackFile ${libcxx.src}
+    unpackFile ${llvm.src}
+    export NIX_CFLAGS_COMPILE+=" -I$PWD/include"
+    export cmakeFlags="-DLLVM_PATH=$PWD/$(ls -d llvm-*) -DLIBCXXABI_LIBCXX_INCLUDES=$PWD/$(ls -d libcxx-*)/include"
+  '' + stdenv.lib.optionalString stdenv.isDarwin ''
+    export TRIPLE=x86_64-apple-darwin
+  '' + stdenv.lib.optionalString stdenv.hostPlatform.isMusl ''
+    patch -p1 -d $(ls -d libcxx-*) -i ${../libcxx-0001-musl-hacks.patch}
+    patch -p1 -d $(ls -d libcxx-*) -i ${../libcxx-max_align_t.patch}
+  '';
+
+  installPhase = if stdenv.isDarwin
+    then ''
+      for file in lib/*.dylib; do
+        # this should be done in CMake, but having trouble figuring out
+        # the magic combination of necessary CMake variables
+        # if you fancy a try, take a look at
+        # http://www.cmake.org/Wiki/CMake_RPATH_handling
+        install_name_tool -id $out/$file $file
+      done
+      make install
+      install -d 755 $out/include
+      install -m 644 ../include/*.h $out/include
+    ''
+    else ''
+      install -d -m 755 $out/include $out/lib
+      install -m 644 lib/libc++abi.so.1.0 $out/lib
+      install -m 644 ../include/cxxabi.h $out/include
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so.1
+    '';
+
+  meta = {
+    homepage = http://libcxxabi.llvm.org/;
+    description = "A new implementation of low level support for a standard C++ library";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    maintainers = with stdenv.lib.maintainers; [ vlstill ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.8/lldb.nix b/nixpkgs/pkgs/development/compilers/llvm/3.8/lldb.nix
new file mode 100644
index 000000000000..d27786464c05
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.8/lldb.nix
@@ -0,0 +1,50 @@
+{ stdenv
+, fetch
+, cmake
+, zlib
+, ncurses
+, swig
+, which
+, libedit
+, llvm
+, clang-unwrapped
+, python
+, version
+}:
+
+stdenv.mkDerivation {
+  name = "lldb-${version}";
+
+  src = fetch "lldb" "18z8vhfgh4m57hl66i83cp4d4mv3i86z2hjhbp5rvqs7d88li49l";
+
+  postUnpack = ''
+    # Hack around broken standalone builf as of 3.8
+    unpackFile ${llvm.src}
+    srcDir="$(ls -d lldb-*.src)"
+    mkdir -p "$srcDir/tools/lib/Support"
+    cp "$(ls -d llvm-*.src)/lib/Support/regex_impl.h" "$srcDir/tools/lib/Support/"
+  '';
+
+  buildInputs = [ cmake python which swig ncurses zlib libedit llvm ];
+
+  hardeningDisable = [ "format" ];
+
+  cmakeFlags = [
+    "-DLLDB_PATH_TO_LLVM_BUILD=${llvm}"
+    "-DLLVM_MAIN_INCLUDE_DIR=${llvm}/include"
+    "-DLLDB_PATH_TO_CLANG_BUILD=${clang-unwrapped}"
+    "-DCLANG_MAIN_INCLUDE_DIR=${clang-unwrapped}/include"
+    "-DPYTHON_VERSION_MAJOR=2"
+    "-DPYTHON_VERSION_MINOR=7"
+    "-DLLDB_DISABLE_LIBEDIT=1" # https://llvm.org/bugs/show_bug.cgi?id=28898
+  ];
+
+  enableParallelBuilding = true;
+
+  meta = {
+    description = "A next-generation high-performance debugger";
+    homepage    = http://llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.8/llvm.nix b/nixpkgs/pkgs/development/compilers/llvm/3.8/llvm.nix
new file mode 100644
index 000000000000..261a1d0f94ca
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.8/llvm.nix
@@ -0,0 +1,117 @@
+{ stdenv
+, fetch
+, fetchpatch
+, perl
+, groff
+, cmake
+, python
+, libffi
+, libbfd
+, libxml2
+, ncurses
+, version
+, zlib
+, compiler-rt_src
+, debugVersion ? false
+, enableSharedLibraries ? true
+}:
+
+let
+  src = fetch "llvm" "1ybmnid4pw2hxn12ax5qa5kl1ldfns0njg8533y3mzslvd5cx0kf";
+in stdenv.mkDerivation rec {
+  name = "llvm-${version}";
+
+  unpackPhase = ''
+    unpackFile ${src}
+    mv llvm-${version}.src llvm
+    sourceRoot=$PWD/llvm
+    unpackFile ${compiler-rt_src}
+    mv compiler-rt-* $sourceRoot/projects/compiler-rt
+  '';
+
+  buildInputs = [ perl groff cmake libxml2 python libffi ];
+
+  propagatedBuildInputs = [ ncurses zlib ];
+
+  # Fix a segfault in llc
+  # See http://lists.llvm.org/pipermail/llvm-dev/2016-October/106500.html
+  patches = [ ./D17533-1.patch ]
+   ++ stdenv.lib.optional (!stdenv.isDarwin) ./fix-llvm-config.patch
+   ++ stdenv.lib.optionals stdenv.hostPlatform.isMusl [
+     ../TLI-musl.patch
+     ../dynamiclibrary-musl.patch
+   ];
+
+  # hacky fix: New LLVM releases require a newer macOS SDK than
+  # 10.9. This is a temporary measure until nixpkgs darwin support is
+  # updated.
+  postPatch = stdenv.lib.optionalString stdenv.isDarwin ''
+    sed -i 's/os_trace(\(.*\)");$/printf(\1\\n");/g' ./projects/compiler-rt/lib/sanitizer_common/sanitizer_mac.cc
+
+    substituteInPlace CMakeLists.txt \
+      --replace 'set(CMAKE_INSTALL_NAME_DIR "@rpath")' "set(CMAKE_INSTALL_NAME_DIR "$out/lib")" \
+      --replace 'set(CMAKE_INSTALL_RPATH "@executable_path/../lib")' ""
+  ''
+  + ''
+    (
+      cd projects/compiler-rt
+      patch -p1 < ${
+        fetchpatch {
+          name = "sigaltstack.patch"; # for glibc-2.26
+          url = https://github.com/llvm-mirror/compiler-rt/commit/8a5e425a68d.diff;
+          sha256 = "0h4y5vl74qaa7dl54b1fcyqalvlpd8zban2d1jxfkxpzyi7m8ifi";
+        }
+      }
+    )
+  '';
+
+  # hacky fix: created binaries need to be run before installation
+  preBuild = ''
+    mkdir -p $out/
+    ln -sv $PWD/lib $out
+  '';
+
+  cmakeFlags = with stdenv; [
+    "-DCMAKE_BUILD_TYPE=${if debugVersion then "Debug" else "Release"}"
+    "-DLLVM_INSTALL_UTILS=ON"  # Needed by rustc
+    "-DLLVM_BUILD_TESTS=ON"
+    "-DLLVM_ENABLE_FFI=ON"
+    "-DLLVM_ENABLE_RTTI=ON"
+
+    "-DLLVM_HOST_TRIPLE=${stdenv.hostPlatform.config}"
+    "-DLLVM_DEFAULT_TARGET_TRIPLE=${stdenv.hostPlatform.config}"
+    "-DTARGET_TRIPLE=${stdenv.hostPlatform.config}"
+  ] ++ stdenv.lib.optional enableSharedLibraries [
+    "-DLLVM_LINK_LLVM_DYLIB=ON"
+  ] ++ stdenv.lib.optional (!isDarwin)
+    "-DLLVM_BINUTILS_INCDIR=${libbfd.dev}/include"
+    ++ stdenv.lib.optionals ( isDarwin) [
+    "-DLLVM_ENABLE_LIBCXX=ON"
+    "-DCAN_TARGET_i386=false"
+  ] ++ stdenv.lib.optionals stdenv.hostPlatform.isMusl [
+    # Not yet supported
+    "-DCOMPILER_RT_BUILD_SANITIZERS=OFF"
+    "-DCOMPILER_RT_BUILD_XRAY=OFF"
+
+  ];
+
+  postBuild = ''
+    rm -fR $out
+  '';
+
+  postInstall = stdenv.lib.optionalString (stdenv.isDarwin && enableSharedLibraries) ''
+    ln -s $out/lib/libLLVM.dylib $out/lib/libLLVM-${version}.dylib
+  '';
+
+  enableParallelBuilding = true;
+
+  passthru.src = src;
+
+  meta = {
+    description = "Collection of modular and reusable compiler and toolchain technologies";
+    homepage    = http://llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    maintainers = with stdenv.lib.maintainers; [ lovek323 raskin ];
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.9/clang/default.nix b/nixpkgs/pkgs/development/compilers/llvm/3.9/clang/default.nix
new file mode 100644
index 000000000000..f597c559dba6
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.9/clang/default.nix
@@ -0,0 +1,79 @@
+{ stdenv, fetch, cmake, libxml2, llvm, version, clang-tools-extra_src, python }:
+
+let
+  gcc = if stdenv.cc.isGNU then stdenv.cc.cc else stdenv.cc.cc.gcc;
+  self = stdenv.mkDerivation {
+    name = "clang-${version}";
+
+    unpackPhase = ''
+      unpackFile ${fetch "cfe" "0qsyyb40iwifhhlx9a3drf8z6ni6zwyk3bvh0kx2gs6yjsxwxi76"}
+      mv cfe-${version}.src clang
+      sourceRoot=$PWD/clang
+      unpackFile ${clang-tools-extra_src}
+      mv clang-tools-extra-* $sourceRoot/tools/extra
+    '';
+
+    nativeBuildInputs = [ cmake ];
+
+    buildInputs = [ libxml2 llvm python ];
+
+    cmakeFlags = [
+      "-DCMAKE_CXX_FLAGS=-std=c++11"
+    ] ++
+    # Maybe with compiler-rt this won't be needed?
+    (stdenv.lib.optional stdenv.isLinux "-DGCC_INSTALL_PREFIX=${gcc}") ++
+    (stdenv.lib.optional (stdenv.cc.libc != null) "-DC_INCLUDE_DIRS=${stdenv.cc.libc}/include");
+
+    patches = [ ./purity.patch ];
+
+    postPatch = ''
+      sed -i -e 's/Args.hasArg(options::OPT_nostdlibinc)/true/' lib/Driver/Tools.cpp
+      sed -i -e 's/DriverArgs.hasArg(options::OPT_nostdlibinc)/true/' lib/Driver/ToolChains.cpp
+    '' + stdenv.lib.optionalString stdenv.hostPlatform.isMusl ''
+      sed -i -e 's/lgcc_s/lgcc_eh/' lib/Driver/Tools.cpp
+    '';
+
+    outputs = [ "out" "lib" "python" ];
+
+    # Clang expects to find LLVMgold in its own prefix
+    # Clang expects to find sanitizer libraries in its own prefix
+    postInstall = ''
+      if [ -e ${llvm}/lib/LLVMgold.so ]; then
+        ln -sv ${llvm}/lib/LLVMgold.so $out/lib
+      fi
+
+      ln -sv ${llvm}/lib/clang/${version}/lib $out/lib/clang/${version}/
+      ln -sv $out/bin/clang $out/bin/cpp
+
+      # Move libclang to 'lib' output
+      moveToOutput "lib/libclang.*" "$lib"
+      substituteInPlace $out/lib/cmake/clang/ClangTargets-release.cmake \
+          --replace "\''${_IMPORT_PREFIX}/lib/libclang." "$lib/lib/libclang."
+
+      mkdir -p $python/bin $python/share/clang/
+      mv $out/bin/{git-clang-format,scan-view} $python/bin
+      if [ -e $out/bin/set-xcode-analyzer ]; then
+        mv $out/bin/set-xcode-analyzer $python/bin
+      fi
+      mv $out/share/clang/*.py $python/share/clang
+
+      rm $out/bin/c-index-test
+    '';
+
+    enableParallelBuilding = true;
+
+    passthru = {
+      isClang = true;
+      inherit llvm;
+    } // stdenv.lib.optionalAttrs stdenv.isLinux {
+      inherit gcc;
+    };
+
+    meta = {
+      description = "A c, c++, objective-c, and objective-c++ frontend for the llvm compiler";
+      homepage    = http://llvm.org/;
+      license     = stdenv.lib.licenses.ncsa;
+      platforms   = stdenv.lib.platforms.all;
+    };
+  };
+in self
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.9/clang/purity.patch b/nixpkgs/pkgs/development/compilers/llvm/3.9/clang/purity.patch
new file mode 100644
index 000000000000..f5fb4c73af47
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.9/clang/purity.patch
@@ -0,0 +1,16 @@
+--- a/lib/Driver/Tools.cpp	2016-08-25 15:48:05.187553443 +0200
++++ b/lib/Driver/Tools.cpp	2016-08-25 15:48:47.534468882 +0200
+@@ -9420,13 +9420,6 @@
+   if (!Args.hasArg(options::OPT_static)) {
+     if (Args.hasArg(options::OPT_rdynamic))
+       CmdArgs.push_back("-export-dynamic");
+-
+-    if (!Args.hasArg(options::OPT_shared)) {
+-      const std::string Loader =
+-          D.DyldPrefix + ToolChain.getDynamicLinker(Args);
+-      CmdArgs.push_back("-dynamic-linker");
+-      CmdArgs.push_back(Args.MakeArgString(Loader));
+-    }
+   }
+ 
+   CmdArgs.push_back("-o");
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.9/default.nix b/nixpkgs/pkgs/development/compilers/llvm/3.9/default.nix
new file mode 100644
index 000000000000..752790cdd853
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.9/default.nix
@@ -0,0 +1,59 @@
+{ newScope, stdenv, libstdcxxHook, isl, fetchurl, overrideCC, wrapCCWith
+, buildLlvmTools # tools, but from the previous stage, for cross
+, targetLlvmLibraries # libraries, but from the next stage, for cross
+}:
+
+let
+  version = "3.9.1";
+
+  fetch = fetch_v version;
+  fetch_v = ver: name: sha256: fetchurl {
+    url = "https://releases.llvm.org/${version}/${name}-${ver}.src.tar.xz";
+    inherit sha256;
+  };
+
+  compiler-rt_src = fetch "compiler-rt" "16gc2gdmp5c800qvydrdhsp0bzb97s8wrakl6i8a4lgslnqnf2fk";
+  clang-tools-extra_src = fetch "clang-tools-extra" "0d9nh7j7brbh9avigcn69dlaihsl9p3cf9s45mw6fxzzvrdvd999";
+
+  tools = stdenv.lib.makeExtensible (tools: let
+    callPackage = newScope (tools // { inherit stdenv isl version fetch; });
+  in {
+    llvm = callPackage ./llvm.nix {
+      inherit compiler-rt_src;
+    };
+
+    clang-unwrapped = callPackage ./clang {
+      inherit clang-tools-extra_src;
+    };
+
+    libclang = tools.clang-unwrapped.lib;
+
+    clang = if stdenv.cc.isGNU then tools.libstdcxxClang else tools.libcxxClang;
+
+    libstdcxxClang = wrapCCWith {
+      cc = tools.clang-unwrapped;
+      extraPackages = [ libstdcxxHook ];
+    };
+
+    libcxxClang = wrapCCWith {
+      cc = tools.clang-unwrapped;
+      extraPackages = [ targetLlvmLibraries.libcxx targetLlvmLibraries.libcxxabi ];
+    };
+
+    lldb = callPackage ./lldb.nix {};
+  });
+
+  libraries = stdenv.lib.makeExtensible (libraries: let
+    callPackage = newScope (libraries // buildLlvmTools // { inherit stdenv isl version fetch; });
+  in {
+
+    stdenv = overrideCC stdenv buildLlvmTools.clang;
+
+    libcxxStdenv = overrideCC stdenv buildLlvmTools.libcxxClang;
+
+    libcxx = callPackage ./libc++ {};
+
+    libcxxabi = callPackage ./libc++abi.nix {};
+  });
+
+in { inherit tools libraries; } // libraries // tools
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.9/libc++/darwin.patch b/nixpkgs/pkgs/development/compilers/llvm/3.9/libc++/darwin.patch
new file mode 100644
index 000000000000..6dd756f01cc2
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.9/libc++/darwin.patch
@@ -0,0 +1,39 @@
+--- libcxx-3.8.0.src.org/lib/CMakeLists.txt	2015-12-16 15:41:05.000000000 -0800
++++ libcxx-3.8.0.src/lib/CMakeLists.txt	2016-06-17 19:40:00.293394500 -0700
+@@ -94,30 +94,30 @@
+     add_definitions(-D__STRICT_ANSI__)
+     add_link_flags(
+       "-compatibility_version 1"
+       "-current_version 1"
+-      "-install_name /usr/lib/libc++.1.dylib"
+-      "-Wl,-reexport_library,/usr/lib/libc++abi.dylib"
++      "-install_name ${LIBCXX_LIBCXXABI_LIB_PATH}/libc++.1.dylib"
++      "-Wl,-reexport_library,${LIBCXX_LIBCXXABI_LIB_PATH}/libc++abi.dylib"
+       "-Wl,-unexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++unexp.exp"
+       "/usr/lib/libSystem.B.dylib")
+   else()
+     if ( ${CMAKE_OSX_SYSROOT} )
+       list(FIND ${CMAKE_OSX_ARCHITECTURES} "armv7" OSX_HAS_ARMV7)
+       if (OSX_HAS_ARMV7)
+         set(OSX_RE_EXPORT_LINE
+-          "${CMAKE_OSX_SYSROOT}/usr/lib/libc++abi.dylib"
++          "${CMAKE_OSX_SYSROOT}${LIBCXX_LIBCXXABI_LIB_PATH}/libc++abi.dylib"
+           "-Wl,-reexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++sjlj-abi.exp")
+       else()
+         set(OSX_RE_EXPORT_LINE
+-          "-Wl,-reexport_library,${CMAKE_OSX_SYSROOT}/usr/lib/libc++abi.dylib")
++          "-Wl,-reexport_library,${CMAKE_OSX_SYSROOT}${LIBCXX_LIBCXXABI_LIB_PATH}/libc++abi.dylib")
+       endif()
+     else()
+-      set(OSX_RE_EXPORT_LINE "/usr/lib/libc++abi.dylib -Wl,-reexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++abi${LIBCXX_LIBCPPABI_VERSION}.exp")
++      set(OSX_RE_EXPORT_LINE "${LIBCXX_LIBCXXABI_LIB_PATH}/libc++abi.dylib -Wl,-reexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++abi${LIBCXX_LIBCPPABI_VERSION}.exp")
+     endif()
+ 
+     add_link_flags(
+       "-compatibility_version 1"
+-      "-install_name /usr/lib/libc++.1.dylib"
++      "-install_name ${LIBCXX_LIBCXXABI_LIB_PATH}/libc++.1.dylib"
+       "-Wl,-unexported_symbols_list,${CMAKE_CURRENT_SOURCE_DIR}/libc++unexp.exp"
+       "${OSX_RE_EXPORT_LINE}"
+       "-Wl,-force_symbols_not_weak_list,${CMAKE_CURRENT_SOURCE_DIR}/notweak.exp"
+       "-Wl,-force_symbols_weak_list,${CMAKE_CURRENT_SOURCE_DIR}/weak.exp")
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.9/libc++/default.nix b/nixpkgs/pkgs/development/compilers/llvm/3.9/libc++/default.nix
new file mode 100644
index 000000000000..bd2cc19d2e0b
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.9/libc++/default.nix
@@ -0,0 +1,51 @@
+{ lib, stdenv, fetch, cmake, libcxxabi, fixDarwinDylibNames, version }:
+
+stdenv.mkDerivation rec {
+  name = "libc++-${version}";
+
+  src = fetch "libcxx" "0qbl3afl2p2h87p977lsqr5kykl6cgjpkzczs0g6a3pn53j1bri5";
+
+  postUnpack = ''
+    unpackFile ${libcxxabi.src}
+  '';
+
+  preConfigure = ''
+    # Get headers from the cxxabi source so we can see private headers not installed by the cxxabi package
+    cmakeFlagsArray=($cmakeFlagsArray -DLIBCXX_CXX_ABI_INCLUDE_PATHS="$NIX_BUILD_TOP/libcxxabi-${version}.src/include")
+  '';
+
+  patches = [
+    # glibc 2.26 fix
+    ./xlocale-glibc-2.26.patch
+  ]
+  ++ lib.optional stdenv.isDarwin ./darwin.patch
+  ++ stdenv.lib.optionals stdenv.hostPlatform.isMusl [
+    ../../libcxx-0001-musl-hacks.patch
+    ../../libcxx-max_align_t.patch
+  ];
+
+  nativeBuildInputs = [ cmake ];
+  buildInputs = [ libcxxabi ] ++ lib.optional stdenv.isDarwin fixDarwinDylibNames;
+
+  cmakeFlags = [
+    "-DLIBCXX_LIBCXXABI_LIB_PATH=${libcxxabi}/lib"
+    "-DLIBCXX_LIBCPPABI_VERSION=2"
+    "-DLIBCXX_CXX_ABI=libcxxabi"
+  ] ++ stdenv.lib.optional stdenv.hostPlatform.isMusl "-DLIBCXX_HAS_MUSL_LIBC=1";
+
+  enableParallelBuilding = true;
+
+  linkCxxAbi = stdenv.isLinux;
+
+  setupHooks = [
+    ../../../../../build-support/setup-hooks/role.bash
+    ./setup-hook.sh
+  ];
+
+  meta = {
+    homepage = http://libcxx.llvm.org/;
+    description = "A new implementation of the C++ standard library, targeting C++11";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.9/libc++/setup-hook.sh b/nixpkgs/pkgs/development/compilers/llvm/3.9/libc++/setup-hook.sh
new file mode 100644
index 000000000000..6611259165ae
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.9/libc++/setup-hook.sh
@@ -0,0 +1,6 @@
+# See pkgs/build-support/setup-hooks/role.bash
+getHostRole
+
+linkCxxAbi="@linkCxxAbi@"
+export NIX_${role_pre}CXXSTDLIB_COMPILE+=" -isystem @out@/include/c++/v1"
+export NIX_${role_pre}CXXSTDLIB_LINK=" -stdlib=libc++${linkCxxAbi:+" -lc++abi"}"
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.9/libc++/xlocale-glibc-2.26.patch b/nixpkgs/pkgs/development/compilers/llvm/3.9/libc++/xlocale-glibc-2.26.patch
new file mode 100644
index 000000000000..4cc042554c85
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.9/libc++/xlocale-glibc-2.26.patch
@@ -0,0 +1,19 @@
+diff --git a/include/__locale b/include/__locale
+index 7bc701d..ea75c86 100644
+--- a/include/__locale
++++ b/include/__locale
+@@ -34,12 +34,12 @@
+ # include <support/solaris/xlocale.h>
+ #elif defined(_NEWLIB_VERSION)
+ # include <support/newlib/xlocale.h>
+-#elif (defined(__GLIBC__) || defined(__APPLE__)      || defined(__FreeBSD__) \
++#elif (defined(__APPLE__)      || defined(__FreeBSD__) \
+     || defined(__EMSCRIPTEN__) || defined(__IBMCPP__))
+ # include <xlocale.h>
+ #elif defined(_LIBCPP_HAS_MUSL_LIBC)
+ # include <support/musl/xlocale.h>
+-#endif // __GLIBC__ || __APPLE__ || __FreeBSD__ || __sun__ || __EMSCRIPTEN__ || __IBMCPP__
++#endif // __APPLE__ || __FreeBSD__ || __sun__ || __EMSCRIPTEN__ || __IBMCPP__
+ 
+ #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+ #pragma GCC system_header
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.9/libc++abi.nix b/nixpkgs/pkgs/development/compilers/llvm/3.9/libc++abi.nix
new file mode 100644
index 000000000000..dffb207a32b6
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.9/libc++abi.nix
@@ -0,0 +1,51 @@
+{ stdenv, cmake, fetch, libcxx, libunwind, llvm, version }:
+
+stdenv.mkDerivation {
+  name = "libc++abi-${version}";
+
+  src = fetch "libcxxabi" "1qi9q06zanqm8awzq83810avmvi52air6gr9zfip8mbg5viqn3cj";
+
+  nativeBuildInputs = [ cmake ];
+  buildInputs = stdenv.lib.optional (!stdenv.isDarwin && !stdenv.isFreeBSD) libunwind;
+
+  postUnpack = ''
+    unpackFile ${libcxx.src}
+    unpackFile ${llvm.src}
+    export NIX_CFLAGS_COMPILE+=" -I$PWD/include"
+    export cmakeFlags="-DLLVM_PATH=$PWD/$(ls -d llvm-*) -DLIBCXXABI_LIBCXX_INCLUDES=$PWD/$(ls -d libcxx-*)/include"
+  '' + stdenv.lib.optionalString stdenv.isDarwin ''
+    export TRIPLE=x86_64-apple-darwin
+  '' + stdenv.lib.optionalString stdenv.hostPlatform.isMusl ''
+    patch -p1 -d $(ls -d libcxx-*) -i ${../libcxx-0001-musl-hacks.patch}
+    patch -p1 -d $(ls -d libcxx-*) -i ${../libcxx-max_align_t.patch}
+  '';
+
+  installPhase = if stdenv.isDarwin
+    then ''
+      for file in lib/*.dylib; do
+        # this should be done in CMake, but having trouble figuring out
+        # the magic combination of necessary CMake variables
+        # if you fancy a try, take a look at
+        # http://www.cmake.org/Wiki/CMake_RPATH_handling
+        install_name_tool -id $out/$file $file
+      done
+      make install
+      install -d 755 $out/include
+      install -m 644 ../include/*.h $out/include
+    ''
+    else ''
+      install -d -m 755 $out/include $out/lib
+      install -m 644 lib/libc++abi.so.1.0 $out/lib
+      install -m 644 ../include/cxxabi.h $out/include
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so.1
+    '';
+
+  meta = {
+    homepage = http://libcxxabi.llvm.org/;
+    description = "A new implementation of low level support for a standard C++ library";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    maintainers = with stdenv.lib.maintainers; [ vlstill ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.9/lldb.nix b/nixpkgs/pkgs/development/compilers/llvm/3.9/lldb.nix
new file mode 100644
index 000000000000..52f27de8cdb5
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.9/lldb.nix
@@ -0,0 +1,56 @@
+{ stdenv
+, fetch
+, cmake
+, zlib
+, ncurses
+, swig
+, which
+, libedit
+, llvm
+, clang-unwrapped
+, python
+, version
+}:
+
+stdenv.mkDerivation {
+  name = "lldb-${version}";
+
+  src = fetch "lldb" "1z30ljmcpp261bjng1i5k3bb9jkrs1cr97z04qs4s3zql6r12cvy";
+
+  postUnpack = ''
+    # Hack around broken standalone build as of 3.8
+    unpackFile ${llvm.src}
+    srcDir="$(ls -d lldb-*.src)"
+    mkdir -p "$srcDir/tools/lib/Support"
+    cp "$(ls -d llvm-*.src)/lib/Support/regex_impl.h" "$srcDir/tools/lib/Support/"
+
+    # Fix up various paths that assume llvm and clang are installed in the same place
+    substituteInPlace $srcDir/cmake/modules/LLDBStandalone.cmake \
+      --replace CheckAtomic $(readlink -f llvm-*.src)/cmake/modules/CheckAtomic.cmake
+    sed -i 's,".*ClangConfig.cmake","${clang-unwrapped}/lib/cmake/clang/ClangConfig.cmake",' \
+      $srcDir/cmake/modules/LLDBStandalone.cmake
+    sed -i 's,".*tools/clang/include","${clang-unwrapped}/include",' \
+      $srcDir/cmake/modules/LLDBStandalone.cmake
+    sed -i 's,"$.LLVM_LIBRARY_DIR.",${llvm}/lib ${clang-unwrapped}/lib,' \
+      $srcDir/cmake/modules/LLDBStandalone.cmake
+  '';
+
+  buildInputs = [ cmake python which swig ncurses zlib libedit llvm ];
+
+  CXXFLAGS = "-fno-rtti";
+  hardeningDisable = [ "format" ];
+
+  cmakeFlags = [
+    "-DLLVM_MAIN_INCLUDE_DIR=${llvm}/include"
+    "-DLLDB_DISABLE_LIBEDIT=1" # https://llvm.org/bugs/show_bug.cgi?id=28898
+  ];
+
+  enableParallelBuilding = true;
+
+  meta = {
+    description = "A next-generation high-performance debugger";
+    homepage    = http://llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.9/llvm-outputs.patch b/nixpkgs/pkgs/development/compilers/llvm/3.9/llvm-outputs.patch
new file mode 100644
index 000000000000..40096fa3497f
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.9/llvm-outputs.patch
@@ -0,0 +1,26 @@
+diff --git a/tools/llvm-config/llvm-config.cpp b/tools/llvm-config/llvm-config.cpp
+index 94d426b..37f7794 100644
+--- a/tools/llvm-config/llvm-config.cpp
++++ b/tools/llvm-config/llvm-config.cpp
+@@ -333,6 +333,21 @@ int main(int argc, char **argv) {
+     ActiveIncludeOption = "-I" + ActiveIncludeDir;
+   }
+ 
++  /// Nix-specific multiple-output handling: override ActiveLibDir if --link-shared
++  if (!IsInDevelopmentTree) {
++    bool WantShared = true;
++    for (int i = 1; i < argc; ++i) {
++      StringRef Arg = argv[i];
++      if (Arg == "--link-shared")
++        WantShared = true;
++      else if (Arg == "--link-static")
++        WantShared = false; // the last one wins
++    }
++
++    if (WantShared)
++      ActiveLibDir = std::string("@lib@") + "/lib" + LLVM_LIBDIR_SUFFIX;
++  }
++
+   /// We only use `shared library` mode in cases where the static library form
+   /// of the components provided are not available; note however that this is
+   /// skipped if we're run from within the build dir. However, once installed,
diff --git a/nixpkgs/pkgs/development/compilers/llvm/3.9/llvm.nix b/nixpkgs/pkgs/development/compilers/llvm/3.9/llvm.nix
new file mode 100644
index 000000000000..6c935fd88de5
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/3.9/llvm.nix
@@ -0,0 +1,171 @@
+{ stdenv
+, fetch
+, fetchpatch
+, perl
+, groff
+, cmake
+, python
+, libffi
+, libbfd
+, libxml2
+, ncurses
+, version
+, zlib
+, compiler-rt_src
+, debugVersion ? false
+, enableSharedLibraries ? (stdenv.buildPlatform == stdenv.hostPlatform)
+, buildPackages
+}:
+
+assert (stdenv.hostPlatform != stdenv.buildPlatform) -> !enableSharedLibraries;
+
+let
+  src = fetch "llvm" "1vi9sf7rx1q04wj479rsvxayb6z740iaz3qniwp266fgp5a07n8z";
+
+  # Used when creating a version-suffixed symlink of libLLVM.dylib
+  shortVersion = with stdenv.lib;
+    concatStringsSep "." (take 2 (splitString "." version));
+in stdenv.mkDerivation rec {
+  name = "llvm-${version}";
+
+  unpackPhase = ''
+    unpackFile ${src}
+    mv llvm-${version}.src llvm
+    sourceRoot=$PWD/llvm
+    unpackFile ${compiler-rt_src}
+    mv compiler-rt-* $sourceRoot/projects/compiler-rt
+  '';
+
+  outputs = [ "out" ] ++ stdenv.lib.optional enableSharedLibraries "lib";
+
+  nativeBuildInputs = [
+    perl
+    cmake
+    python
+  ];
+
+  buildInputs = [
+    groff
+    libxml2
+    libffi
+  ];
+
+  propagatedBuildInputs = [ ncurses zlib ];
+
+  patches = [
+    # fix output of llvm-config (fixed in llvm 4.0)
+    (fetchpatch {
+      url = https://github.com/llvm-mirror/llvm/commit/5340b5b3d970069aebf3dde49d8964583742e01a.patch;
+      sha256 = "095f8knplwqbc2p7rad1kq8633i34qynni9jna93an7kyc80wdxl";
+   })
+   ] ++ stdenv.lib.optionals stdenv.hostPlatform.isMusl [
+     ../TLI-musl.patch
+     ../dynamiclibrary-musl.patch
+   ];
+
+  postPatch = ""
+  + ''
+    patch -p1 --reverse < ${fetchpatch {
+      name = "fix-red-icons.diff"; # https://bugs.freedesktop.org/show_bug.cgi?id=99078
+      url = https://github.com/llvm-mirror/llvm/commit/c280d74837d8.diff;
+      sha256 = "11sq86spw41v72f676igksapdlsgh7fiqp5qkkmgfj0ndqcn9skf";
+    }}
+  ''
+  # TSAN requires XPC on Darwin, which we have no public/free source files for. We can depend on the Apple frameworks
+  # to get it, but they're unfree. Since LLVM is rather central to the stdenv, we patch out TSAN support so that Hydra
+  # can build this. If we didn't do it, basically the entire nixpkgs on Darwin would have an unfree dependency and we'd
+  # get no binary cache for the entire platform. If you really find yourself wanting the TSAN, make this controllable by
+  # a flag and turn the flag off during the stdenv build. I realize that this LLVM isn't used in the stdenv but I want to
+  # keep it consistent with 4.0. We really shouldn't be copying and pasting all this code around...
+  + stdenv.lib.optionalString stdenv.isDarwin ''
+    substituteInPlace ./projects/compiler-rt/cmake/config-ix.cmake \
+      --replace 'set(COMPILER_RT_HAS_TSAN TRUE)' 'set(COMPILER_RT_HAS_TSAN FALSE)'
+
+    substituteInPlace CMakeLists.txt \
+      --replace 'set(CMAKE_INSTALL_NAME_DIR "@rpath")' "set(CMAKE_INSTALL_NAME_DIR "$lib/lib")" \
+      --replace 'set(CMAKE_INSTALL_RPATH "@executable_path/../lib")' ""
+  ''
+  # Patch llvm-config to return correct library path based on --link-{shared,static}.
+  + stdenv.lib.optionalString (enableSharedLibraries) ''
+    substitute '${./llvm-outputs.patch}' ./llvm-outputs.patch --subst-var lib
+    patch -p1 < ./llvm-outputs.patch
+  ''
+  + ''
+    (
+      cd projects/compiler-rt
+      patch -p1 < ${
+        fetchpatch {
+          name = "sigaltstack.patch"; # for glibc-2.26
+          url = https://github.com/llvm-mirror/compiler-rt/commit/8a5e425a68d.diff;
+          sha256 = "0h4y5vl74qaa7dl54b1fcyqalvlpd8zban2d1jxfkxpzyi7m8ifi";
+        }
+      }
+      substituteInPlace lib/esan/esan_sideline_linux.cpp \
+        --replace 'struct sigaltstack' 'stack_t'
+    )
+  '';
+
+  # hacky fix: created binaries need to be run before installation
+  preBuild = ''
+    mkdir -p $out/
+    ln -sv $PWD/lib $out
+  '';
+
+  cmakeFlags = with stdenv; [
+    "-DCMAKE_BUILD_TYPE=${if debugVersion then "Debug" else "Release"}"
+    "-DLLVM_INSTALL_UTILS=ON"  # Needed by rustc
+    "-DLLVM_BUILD_TESTS=ON"
+    "-DLLVM_ENABLE_FFI=ON"
+    "-DLLVM_ENABLE_RTTI=ON"
+    "-DCOMPILER_RT_INCLUDE_TESTS=OFF" # FIXME: requires clang source code
+
+    "-DLLVM_HOST_TRIPLE=${stdenv.hostPlatform.config}"
+    "-DLLVM_DEFAULT_TARGET_TRIPLE=${stdenv.hostPlatform.config}"
+    "-DTARGET_TRIPLE=${stdenv.hostPlatform.config}"
+  ] ++ stdenv.lib.optional enableSharedLibraries [
+    "-DLLVM_LINK_LLVM_DYLIB=ON"
+  ] ++ stdenv.lib.optional (!isDarwin)
+    "-DLLVM_BINUTILS_INCDIR=${libbfd.dev}/include"
+    ++ stdenv.lib.optionals (isDarwin) [
+    "-DLLVM_ENABLE_LIBCXX=ON"
+    "-DCAN_TARGET_i386=false"
+  ] ++ stdenv.lib.optionals (stdenv.buildPlatform != stdenv.hostPlatform) [
+    "-DCMAKE_CROSSCOMPILING=True"
+    "-DLLVM_TABLEGEN=${buildPackages.llvmPackages_39.llvm}/bin/llvm-tblgen"
+  ] ++ stdenv.lib.optionals stdenv.hostPlatform.isMusl [
+    # Not yet supported
+    "-DCOMPILER_RT_BUILD_SANITIZERS=OFF"
+    "-DCOMPILER_RT_BUILD_XRAY=OFF"
+
+  ];
+
+  postBuild = ''
+    rm -fR $out
+  '';
+
+  postInstall = ""
+  + stdenv.lib.optionalString (enableSharedLibraries) ''
+    moveToOutput "lib/libLLVM-*" "$lib"
+    moveToOutput "lib/libLLVM${stdenv.hostPlatform.extensions.sharedLibrary}" "$lib"
+    substituteInPlace "$out/lib/cmake/llvm/LLVMExports-release.cmake" \
+      --replace "\''${_IMPORT_PREFIX}/lib/libLLVM-" "$lib/lib/libLLVM-"
+  ''
+  + stdenv.lib.optionalString (stdenv.isDarwin && enableSharedLibraries) ''
+    substituteInPlace "$out/lib/cmake/llvm/LLVMExports-release.cmake" \
+      --replace "\''${_IMPORT_PREFIX}/lib/libLLVM.dylib" "$lib/lib/libLLVM.dylib"
+    ln -s $lib/lib/libLLVM.dylib $lib/lib/libLLVM-${shortVersion}.dylib
+    ln -s $lib/lib/libLLVM.dylib $lib/lib/libLLVM-${version}.dylib
+  '';
+
+  enableParallelBuilding = true;
+
+  passthru.src = src;
+
+  meta = {
+    description = "Collection of modular and reusable compiler and toolchain technologies";
+    homepage    = http://llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    maintainers = with stdenv.lib.maintainers; [ lovek323 raskin ];
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/4/clang/default.nix b/nixpkgs/pkgs/development/compilers/llvm/4/clang/default.nix
new file mode 100644
index 000000000000..c6538282f23e
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/4/clang/default.nix
@@ -0,0 +1,110 @@
+{ stdenv, fetch, cmake, libxml2, llvm, version, release_version, clang-tools-extra_src, python
+, fixDarwinDylibNames
+, enableManpages ? false
+}:
+
+let
+  gcc = if stdenv.cc.isGNU then stdenv.cc.cc else stdenv.cc.cc.gcc;
+  self = stdenv.mkDerivation ({
+    name = "clang-${version}";
+
+    unpackPhase = ''
+      unpackFile ${fetch "cfe" "16vnv3msnvx33dydd17k2cq0icndi1a06bg5vcxkrhjjb1rqlwv1"}
+      mv cfe-${version}* clang
+      sourceRoot=$PWD/clang
+      unpackFile ${clang-tools-extra_src}
+      mv clang-tools-extra-* $sourceRoot/tools/extra
+    '';
+
+    nativeBuildInputs = [ cmake python ]
+      ++ stdenv.lib.optional enableManpages python.pkgs.sphinx;
+
+    buildInputs = [ libxml2 llvm ]
+      ++ stdenv.lib.optional stdenv.isDarwin fixDarwinDylibNames;
+
+    cmakeFlags = [
+      "-DCMAKE_CXX_FLAGS=-std=c++11"
+    ] ++ stdenv.lib.optionals enableManpages [
+      "-DCLANG_INCLUDE_DOCS=ON"
+      "-DLLVM_ENABLE_SPHINX=ON"
+      "-DSPHINX_OUTPUT_MAN=ON"
+      "-DSPHINX_OUTPUT_HTML=OFF"
+      "-DSPHINX_WARNINGS_AS_ERRORS=OFF"
+    ]
+    # Maybe with compiler-rt this won't be needed?
+    ++ stdenv.lib.optional stdenv.isLinux "-DGCC_INSTALL_PREFIX=${gcc}"
+    ++ stdenv.lib.optional (stdenv.cc.libc != null) "-DC_INCLUDE_DIRS=${stdenv.cc.libc}/include";
+
+    patches = [ ./purity.patch ];
+
+    postPatch = ''
+      sed -i -e 's/Args.hasArg(options::OPT_nostdlibinc)/true/' lib/Driver/Tools.cpp
+      sed -i -e 's/DriverArgs.hasArg(options::OPT_nostdlibinc)/true/' lib/Driver/ToolChains.cpp
+
+      # Patch for standalone doc building
+      sed -i '1s,^,find_package(Sphinx REQUIRED)\n,' docs/CMakeLists.txt
+    '' + stdenv.lib.optionalString stdenv.hostPlatform.isMusl ''
+      sed -i -e 's/lgcc_s/lgcc_eh/' lib/Driver/Tools.cpp
+    '';
+
+    outputs = [ "out" "lib" "python" ];
+
+    # Clang expects to find LLVMgold in its own prefix
+    # Clang expects to find sanitizer libraries in its own prefix
+    postInstall = ''
+      if [ -e ${llvm}/lib/LLVMgold.so ]; then
+        ln -sv ${llvm}/lib/LLVMgold.so $out/lib
+      fi
+
+      ln -sv ${llvm}/lib/clang/${release_version}/lib $out/lib/clang/${release_version}/
+      ln -sv $out/bin/clang $out/bin/cpp
+
+      # Move libclang to 'lib' output
+      moveToOutput "lib/libclang.*" "$lib"
+      substituteInPlace $out/lib/cmake/clang/ClangTargets-release.cmake \
+          --replace "\''${_IMPORT_PREFIX}/lib/libclang." "$lib/lib/libclang."
+
+      mkdir -p $python/bin $python/share/clang/
+      mv $out/bin/{git-clang-format,scan-view} $python/bin
+      if [ -e $out/bin/set-xcode-analyzer ]; then
+        mv $out/bin/set-xcode-analyzer $python/bin
+      fi
+      mv $out/share/clang/*.py $python/share/clang
+      rm $out/bin/c-index-test
+    '';
+
+    enableParallelBuilding = true;
+
+    passthru = {
+      isClang = true;
+      inherit llvm;
+    } // stdenv.lib.optionalAttrs stdenv.isLinux {
+      inherit gcc;
+    };
+
+    meta = {
+      description = "A c, c++, objective-c, and objective-c++ frontend for the llvm compiler";
+      homepage    = http://llvm.org/;
+      license     = stdenv.lib.licenses.ncsa;
+      platforms   = stdenv.lib.platforms.all;
+    };
+  } // stdenv.lib.optionalAttrs enableManpages {
+    name = "clang-manpages-${version}";
+
+    buildPhase = ''
+      make docs-clang-man
+    '';
+
+    installPhase = ''
+      mkdir -p $out/share/man/man1
+      # Manually install clang manpage
+      cp docs/man/*.1 $out/share/man/man1/
+    '';
+
+    outputs = [ "out" ];
+
+    doCheck = false;
+
+    meta.description = "man page for Clang ${version}";
+  });
+in self
diff --git a/nixpkgs/pkgs/development/compilers/llvm/4/clang/purity.patch b/nixpkgs/pkgs/development/compilers/llvm/4/clang/purity.patch
new file mode 100644
index 000000000000..f5fb4c73af47
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/4/clang/purity.patch
@@ -0,0 +1,16 @@
+--- a/lib/Driver/Tools.cpp	2016-08-25 15:48:05.187553443 +0200
++++ b/lib/Driver/Tools.cpp	2016-08-25 15:48:47.534468882 +0200
+@@ -9420,13 +9420,6 @@
+   if (!Args.hasArg(options::OPT_static)) {
+     if (Args.hasArg(options::OPT_rdynamic))
+       CmdArgs.push_back("-export-dynamic");
+-
+-    if (!Args.hasArg(options::OPT_shared)) {
+-      const std::string Loader =
+-          D.DyldPrefix + ToolChain.getDynamicLinker(Args);
+-      CmdArgs.push_back("-dynamic-linker");
+-      CmdArgs.push_back(Args.MakeArgString(Loader));
+-    }
+   }
+ 
+   CmdArgs.push_back("-o");
diff --git a/nixpkgs/pkgs/development/compilers/llvm/4/cmdline-help.patch b/nixpkgs/pkgs/development/compilers/llvm/4/cmdline-help.patch
new file mode 100644
index 000000000000..a693719c2cfa
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/4/cmdline-help.patch
@@ -0,0 +1,39 @@
+From c7a9aa3a697c81432786a5583bf973771c7be15e Mon Sep 17 00:00:00 2001
+From: Don Hinton <hintonda@gmail.com>
+Date: Wed, 12 Jul 2017 01:15:46 +0000
+Subject: [PATCH] Fix minor typo introduced in r276404
+
+Summary:
+A space was added between '-' and 'help' when emitting help output.
+
+See https://reviews.llvm.org/D22621 for details.
+
+Reviewers: MaggieYi, vsk
+
+Reviewed By: vsk
+
+Subscribers: llvm-commits
+
+Differential Revision: https://reviews.llvm.org/D35283
+
+git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@307745 91177308-0d34-0410-b5e6-96231b3b80d8
+---
+ lib/Support/CommandLine.cpp | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/lib/Support/CommandLine.cpp b/lib/Support/CommandLine.cpp
+index 3889902eea5..79defa5c36c 100644
+--- a/lib/Support/CommandLine.cpp
++++ b/lib/Support/CommandLine.cpp
+@@ -1236,7 +1236,7 @@ bool CommandLineParser::ParseCommandLineOptions(int argc,
+              << ": Not enough positional command line arguments specified!\n"
+              << "Must specify at least " << NumPositionalRequired
+              << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
+-             << ": See: " << argv[0] << " - help\n";
++             << ": See: " << argv[0] << " -help\n";
+     }
+ 
+     ErrorParsing = true;
+-- 
+2.14.0
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/4/default.nix b/nixpkgs/pkgs/development/compilers/llvm/4/default.nix
new file mode 100644
index 000000000000..9651dbb72f4d
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/4/default.nix
@@ -0,0 +1,74 @@
+{ lowPrio, newScope, pkgs, stdenv, cmake, libstdcxxHook
+, libxml2, python, isl, fetchurl, overrideCC, wrapCCWith
+, buildLlvmTools # tools, but from the previous stage, for cross
+, targetLlvmLibraries # libraries, but from the next stage, for cross
+}:
+
+let
+  release_version = "4.0.1";
+  version = release_version; # differentiating these is important for rc's
+
+  fetch = name: sha256: fetchurl {
+    url = "https://releases.llvm.org/${release_version}/${name}-${version}.src.tar.xz";
+    inherit sha256;
+  };
+
+  compiler-rt_src = fetch "compiler-rt" "0h5lpv1z554szi4r4blbskhwrkd78ir50v3ng8xvk1s86fa7gj53";
+  clang-tools-extra_src = fetch "clang-tools-extra" "1dhmp7ccfpr42bmvk3kp37ngjpf3a9m5d4kkpsn7d00hzi7fdl9m";
+
+  tools = stdenv.lib.makeExtensible (tools: let
+    callPackage = newScope (tools // { inherit stdenv cmake libxml2 python isl release_version version fetch; });
+  in {
+
+    llvm = callPackage ./llvm.nix {
+      inherit compiler-rt_src;
+    };
+    clang-unwrapped = callPackage ./clang {
+      inherit clang-tools-extra_src;
+    };
+
+    llvm-manpages = lowPrio (tools.llvm.override {
+      enableManpages = true;
+      python = pkgs.python;  # don't use python-boot
+    });
+
+    clang-manpages = lowPrio (tools.clang-unwrapped.override {
+      enableManpages = true;
+      python = pkgs.python;  # don't use python-boot
+    });
+
+    libclang = tools.clang-unwrapped.lib;
+
+    clang = if stdenv.cc.isGNU then tools.libstdcxxClang else tools.libcxxClang;
+
+    libstdcxxClang = wrapCCWith {
+      cc = tools.clang-unwrapped;
+      extraPackages = [ libstdcxxHook ];
+    };
+
+    libcxxClang = wrapCCWith {
+      cc = tools.clang-unwrapped;
+      extraPackages = [ targetLlvmLibraries.libcxx targetLlvmLibraries.libcxxabi ];
+    };
+
+    lld = callPackage ./lld.nix {};
+
+    lldb = callPackage ./lldb.nix {};
+  });
+
+  libraries = stdenv.lib.makeExtensible (libraries: let
+    callPackage = newScope (libraries // buildLlvmTools // { inherit stdenv cmake libxml2 python isl release_version version fetch; });
+  in {
+
+    stdenv = overrideCC stdenv buildLlvmTools.clang;
+
+    libcxxStdenv = overrideCC stdenv buildLlvmTools.libcxxClang;
+
+    libcxx = callPackage ./libc++ {};
+
+    libcxxabi = callPackage ./libc++abi.nix {};
+
+    openmp = callPackage ./openmp.nix {};
+  });
+
+in { inherit tools libraries; } // libraries // tools
diff --git a/nixpkgs/pkgs/development/compilers/llvm/4/libc++/default.nix b/nixpkgs/pkgs/development/compilers/llvm/4/libc++/default.nix
new file mode 100644
index 000000000000..2b543b9d793a
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/4/libc++/default.nix
@@ -0,0 +1,58 @@
+{ lib, stdenv, fetch, cmake, python, libcxxabi, fixDarwinDylibNames, version }:
+
+stdenv.mkDerivation rec {
+  name = "libc++-${version}";
+
+  src = fetch "libcxx" "0k6cmjcxnp2pyl8xwy1wkyyckkmdrjddim94yf1gzjbjy9qi22jj";
+
+  postUnpack = ''
+    unpackFile ${libcxxabi.src}
+    export LIBCXXABI_INCLUDE_DIR="$PWD/$(ls -d libcxxabi-${version}*)/include"
+  '';
+
+  patches = [
+    # https://github.com/llvm-mirror/libcxx/commit/bcc92d75df0274b9593ebd097fcae60494e3bffc
+    ./pthread_mach_thread_np.patch
+    # glibc 2.26 fix
+    ./xlocale-glibc-2.26.patch
+  ] ++ stdenv.lib.optionals stdenv.hostPlatform.isMusl [
+    ../../libcxx-0001-musl-hacks.patch
+    ../../libcxx-max_align_t.patch
+  ];
+
+  prePatch = ''
+    substituteInPlace lib/CMakeLists.txt --replace "/usr/lib/libc++" "\''${LIBCXX_LIBCXXABI_LIB_PATH}/libc++"
+  '';
+
+  preConfigure = ''
+    # Get headers from the cxxabi source so we can see private headers not installed by the cxxabi package
+    cmakeFlagsArray=($cmakeFlagsArray -DLIBCXX_CXX_ABI_INCLUDE_PATHS="$LIBCXXABI_INCLUDE_DIR")
+  '' + lib.optionalString stdenv.hostPlatform.isMusl ''
+    patchShebangs utils/cat_files.py
+  '';
+  nativeBuildInputs = [ cmake ] ++ stdenv.lib.optional stdenv.hostPlatform.isMusl python;
+
+  buildInputs = [ libcxxabi ] ++ lib.optional stdenv.isDarwin fixDarwinDylibNames;
+
+  cmakeFlags = [
+    "-DLIBCXX_LIBCXXABI_LIB_PATH=${libcxxabi}/lib"
+    "-DLIBCXX_LIBCPPABI_VERSION=2"
+    "-DLIBCXX_CXX_ABI=libcxxabi"
+  ] ++ stdenv.lib.optional stdenv.hostPlatform.isMusl "-DLIBCXX_HAS_MUSL_LIBC=1";
+
+  enableParallelBuilding = true;
+
+  linkCxxAbi = stdenv.isLinux;
+
+  setupHooks = [
+    ../../../../../build-support/setup-hooks/role.bash
+    ./setup-hook.sh
+  ];
+
+  meta = {
+    homepage = http://libcxx.llvm.org/;
+    description = "A new implementation of the C++ standard library, targeting C++11";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/4/libc++/pthread_mach_thread_np.patch b/nixpkgs/pkgs/development/compilers/llvm/4/libc++/pthread_mach_thread_np.patch
new file mode 100644
index 000000000000..8c71f1b815db
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/4/libc++/pthread_mach_thread_np.patch
@@ -0,0 +1,41 @@
+From bcc92d75df0274b9593ebd097fcae60494e3bffc Mon Sep 17 00:00:00 2001
+From: Asiri Rathnayake <asiri.rathnayake@arm.com>
+Date: Thu, 26 Jan 2017 10:40:17 +0000
+Subject: [PATCH] Fix chromium build (libcxx)
+
+Remove the reference to pthread_mach_thread_np() in libcxx headers.
+
+git-svn-id: https://llvm.org/svn/llvm-project/libcxx/trunk@293167 91177308-0d34-0410-b5e6-96231b3b80d8
+---
+ include/__threading_support | 11 -----------
+ 1 file changed, 11 deletions(-)
+
+diff --git a/include/__threading_support b/include/__threading_support
+index 13ab769..dfe7fe1 100644
+--- a/include/__threading_support
++++ b/include/__threading_support
+@@ -149,11 +149,6 @@ int __libcpp_execute_once(__libcpp_exec_once_flag *flag,
+                           void (*init_routine)(void));
+ 
+ // Thread id
+-#if defined(__APPLE__) && !defined(__arm__)
+-_LIBCPP_THREAD_ABI_VISIBILITY
+-mach_port_t __libcpp_thread_get_port();
+-#endif
+-
+ _LIBCPP_THREAD_ABI_VISIBILITY
+ bool __libcpp_thread_id_equal(__libcpp_thread_id t1, __libcpp_thread_id t2);
+ 
+@@ -297,12 +292,6 @@ int __libcpp_execute_once(__libcpp_exec_once_flag *flag,
+ }
+ 
+ // Thread id
+-#if defined(__APPLE__) && !defined(__arm__)
+-mach_port_t __libcpp_thread_get_port() {
+-    return pthread_mach_thread_np(pthread_self());
+-}
+-#endif
+-
+ // Returns non-zero if the thread ids are equal, otherwise 0
+ bool __libcpp_thread_id_equal(__libcpp_thread_id t1, __libcpp_thread_id t2)
+ {
diff --git a/nixpkgs/pkgs/development/compilers/llvm/4/libc++/setup-hook.sh b/nixpkgs/pkgs/development/compilers/llvm/4/libc++/setup-hook.sh
new file mode 100644
index 000000000000..6611259165ae
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/4/libc++/setup-hook.sh
@@ -0,0 +1,6 @@
+# See pkgs/build-support/setup-hooks/role.bash
+getHostRole
+
+linkCxxAbi="@linkCxxAbi@"
+export NIX_${role_pre}CXXSTDLIB_COMPILE+=" -isystem @out@/include/c++/v1"
+export NIX_${role_pre}CXXSTDLIB_LINK=" -stdlib=libc++${linkCxxAbi:+" -lc++abi"}"
diff --git a/nixpkgs/pkgs/development/compilers/llvm/4/libc++/xlocale-glibc-2.26.patch b/nixpkgs/pkgs/development/compilers/llvm/4/libc++/xlocale-glibc-2.26.patch
new file mode 100644
index 000000000000..e411d85066b4
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/4/libc++/xlocale-glibc-2.26.patch
@@ -0,0 +1,19 @@
+diff --git a/include/__locale b/include/__locale
+index f4882de..29443b4 100644
+--- a/include/__locale
++++ b/include/__locale
+@@ -34,12 +34,12 @@
+ # include <support/solaris/xlocale.h>
+ #elif defined(_NEWLIB_VERSION)
+ # include <support/newlib/xlocale.h>
+-#elif (defined(__GLIBC__) || defined(__APPLE__)      || defined(__FreeBSD__) \
++#elif (defined(__APPLE__)      || defined(__FreeBSD__) \
+     || defined(__EMSCRIPTEN__) || defined(__IBMCPP__))
+ # include <xlocale.h>
+ #elif defined(_LIBCPP_HAS_MUSL_LIBC)
+ # include <support/musl/xlocale.h>
+-#endif // __GLIBC__ || __APPLE__ || __FreeBSD__ || __sun__ || __EMSCRIPTEN__ || __IBMCPP__
++#endif // __APPLE__ || __FreeBSD__ || __sun__ || __EMSCRIPTEN__ || __IBMCPP__
+ 
+ #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+ #pragma GCC system_header
diff --git a/nixpkgs/pkgs/development/compilers/llvm/4/libc++abi.nix b/nixpkgs/pkgs/development/compilers/llvm/4/libc++abi.nix
new file mode 100644
index 000000000000..735c5e9e7435
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/4/libc++abi.nix
@@ -0,0 +1,51 @@
+{ stdenv, cmake, fetch, libcxx, libunwind, llvm, version }:
+
+stdenv.mkDerivation {
+  name = "libc++abi-${version}";
+
+  src = fetch "libcxxabi" "0cqvzallxh0nwiijsf6i4d5ds9m5ijfzywg7376ncv50i64if24g";
+
+  nativeBuildInputs = [ cmake ];
+  buildInputs = stdenv.lib.optional (!stdenv.isDarwin && !stdenv.isFreeBSD) libunwind;
+
+  postUnpack = ''
+    unpackFile ${libcxx.src}
+    unpackFile ${llvm.src}
+    export cmakeFlags="-DLLVM_PATH=$PWD/$(ls -d llvm-*) -DLIBCXXABI_LIBCXX_PATH=$PWD/$(ls -d libcxx-*)"
+  '' + stdenv.lib.optionalString stdenv.isDarwin ''
+    export TRIPLE=x86_64-apple-darwin
+  '' + stdenv.lib.optionalString stdenv.hostPlatform.isMusl ''
+    patch -p1 -d $(ls -d libcxx-*) -i ${../libcxx-0001-musl-hacks.patch}
+    patch -p1 -d $(ls -d libcxx-*) -i ${../libcxx-max_align_t.patch}
+  '';
+
+  installPhase = if stdenv.isDarwin
+    then ''
+      for file in lib/*.dylib; do
+        # this should be done in CMake, but having trouble figuring out
+        # the magic combination of necessary CMake variables
+        # if you fancy a try, take a look at
+        # http://www.cmake.org/Wiki/CMake_RPATH_handling
+        install_name_tool -id $out/$file $file
+      done
+      make install
+      install -d 755 $out/include
+      install -m 644 ../include/*.h $out/include
+    ''
+    else ''
+      install -d -m 755 $out/include $out/lib
+      install -m 644 lib/libc++abi.a $out/lib
+      install -m 644 lib/libc++abi.so.1.0 $out/lib
+      install -m 644 ../include/cxxabi.h $out/include
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so.1
+    '';
+
+  meta = {
+    homepage = http://libcxxabi.llvm.org/;
+    description = "A new implementation of low level support for a standard C++ library";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    maintainers = with stdenv.lib.maintainers; [ vlstill ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/4/lld.nix b/nixpkgs/pkgs/development/compilers/llvm/4/lld.nix
new file mode 100644
index 000000000000..21b0c1c3601c
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/4/lld.nix
@@ -0,0 +1,31 @@
+{ stdenv
+, fetch
+, cmake
+, llvm
+, version
+}:
+
+stdenv.mkDerivation {
+  name = "lld-${version}";
+
+  src = fetch "lld" "1v9nkpr158j4yd4zmi6rpnfxkp78r1fapr8wji9s6v176gji1kk3";
+
+  nativeBuildInputs = [ cmake ];
+  buildInputs = [ llvm ];
+
+  outputs = [ "out" "dev" ];
+
+  enableParallelBuilding = true;
+
+  postInstall = ''
+    moveToOutput include "$dev"
+    moveToOutput lib "$dev"
+  '';
+
+  meta = {
+    description = "The LLVM Linker";
+    homepage    = http://lld.llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/4/lldb-libedit.patch b/nixpkgs/pkgs/development/compilers/llvm/4/lldb-libedit.patch
new file mode 100644
index 000000000000..73459ce6c864
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/4/lldb-libedit.patch
@@ -0,0 +1,30 @@
+From 94764369222a8e6c65420a6981d7f179a18a5417 Mon Sep 17 00:00:00 2001
+From: Will Dietz <w@wdtz.org>
+Date: Thu, 25 May 2017 15:03:42 -0500
+Subject: [PATCH] EditLine.h: libedit supports wide chars on NixOS
+
+---
+ include/lldb/Host/Editline.h | 5 +----
+ 1 file changed, 1 insertion(+), 4 deletions(-)
+
+diff --git a/include/lldb/Host/Editline.h b/include/lldb/Host/Editline.h
+index faed373bc..b248cdee1 100644
+--- a/include/lldb/Host/Editline.h
++++ b/include/lldb/Host/Editline.h
+@@ -43,12 +43,9 @@
+ // will only be
+ // used in cases where this is true.  This is a compile time dependecy, for now
+ // selected per target Platform
+-#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
++// (libedit on NixOS is always wide-char capable)
+ #define LLDB_EDITLINE_USE_WCHAR 1
+ #include <codecvt>
+-#else
+-#define LLDB_EDITLINE_USE_WCHAR 0
+-#endif
+ 
+ #include "lldb/Host/ConnectionFileDescriptor.h"
+ #include "lldb/lldb-private.h"
+-- 
+2.13.0
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/4/lldb.nix b/nixpkgs/pkgs/development/compilers/llvm/4/lldb.nix
new file mode 100644
index 000000000000..0be8a4d41865
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/4/lldb.nix
@@ -0,0 +1,62 @@
+{ stdenv
+, fetch
+, cmake
+, zlib
+, ncurses
+, swig
+, which
+, libedit
+, libxml2
+, llvm
+, clang-unwrapped
+, python
+, version
+, darwin
+}:
+
+stdenv.mkDerivation {
+  name = "lldb-${version}";
+
+  src = fetch "lldb" "0yy43a27zx3r51b6gkv3v2mdiqcq3mf0ngki47ya0i30v3gx4cl4";
+
+  patches = [ ./lldb-libedit.patch ];
+  postPatch = ''
+    # Fix up various paths that assume llvm and clang are installed in the same place
+    sed -i 's,".*ClangConfig.cmake","${clang-unwrapped}/lib/cmake/clang/ClangConfig.cmake",' \
+      cmake/modules/LLDBStandalone.cmake
+    sed -i 's,".*tools/clang/include","${clang-unwrapped}/include",' \
+      cmake/modules/LLDBStandalone.cmake
+    sed -i 's,"$.LLVM_LIBRARY_DIR.",${llvm}/lib ${clang-unwrapped}/lib,' \
+      cmake/modules/LLDBStandalone.cmake
+  '';
+
+  nativeBuildInputs = [ cmake python which swig ];
+  buildInputs = [ ncurses zlib libedit libxml2 llvm ]
+    ++ stdenv.lib.optionals stdenv.isDarwin [ darwin.libobjc darwin.apple_sdk.libs.xpc darwin.apple_sdk.frameworks.Foundation darwin.bootstrap_cmds darwin.apple_sdk.frameworks.Carbon darwin.apple_sdk.frameworks.Cocoa darwin.cf-private ];
+
+  CXXFLAGS = "-fno-rtti";
+  hardeningDisable = [ "format" ];
+
+  cmakeFlags = [
+    "-DLLDB_CODESIGN_IDENTITY=" # codesigning makes nondeterministic
+  ];
+
+  # Add missing include to fix error when using std::bind
+  prePatch = ''
+    sed -i -e '30i#include <functional>' include/lldb/Utility/TaskPool.h
+  '';
+
+  enableParallelBuilding = true;
+
+  postInstall = ''
+    mkdir -p $out/share/man/man1
+    cp ../docs/lldb.1 $out/share/man/man1/
+  '';
+
+  meta = with stdenv.lib; {
+    description = "A next-generation high-performance debugger";
+    homepage    = http://llvm.org/;
+    license     = licenses.ncsa;
+    platforms   = platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/4/llvm-outputs.patch b/nixpkgs/pkgs/development/compilers/llvm/4/llvm-outputs.patch
new file mode 100644
index 000000000000..40096fa3497f
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/4/llvm-outputs.patch
@@ -0,0 +1,26 @@
+diff --git a/tools/llvm-config/llvm-config.cpp b/tools/llvm-config/llvm-config.cpp
+index 94d426b..37f7794 100644
+--- a/tools/llvm-config/llvm-config.cpp
++++ b/tools/llvm-config/llvm-config.cpp
+@@ -333,6 +333,21 @@ int main(int argc, char **argv) {
+     ActiveIncludeOption = "-I" + ActiveIncludeDir;
+   }
+ 
++  /// Nix-specific multiple-output handling: override ActiveLibDir if --link-shared
++  if (!IsInDevelopmentTree) {
++    bool WantShared = true;
++    for (int i = 1; i < argc; ++i) {
++      StringRef Arg = argv[i];
++      if (Arg == "--link-shared")
++        WantShared = true;
++      else if (Arg == "--link-static")
++        WantShared = false; // the last one wins
++    }
++
++    if (WantShared)
++      ActiveLibDir = std::string("@lib@") + "/lib" + LLVM_LIBDIR_SUFFIX;
++  }
++
+   /// We only use `shared library` mode in cases where the static library form
+   /// of the components provided are not available; note however that this is
+   /// skipped if we're run from within the build dir. However, once installed,
diff --git a/nixpkgs/pkgs/development/compilers/llvm/4/llvm.nix b/nixpkgs/pkgs/development/compilers/llvm/4/llvm.nix
new file mode 100644
index 000000000000..5cd7901fe22c
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/4/llvm.nix
@@ -0,0 +1,176 @@
+{ stdenv
+, fetch
+, fetchpatch
+, cmake
+, python
+, libffi
+, libbfd
+, libxml2
+, ncurses
+, version
+, release_version
+, zlib
+, compiler-rt_src
+, debugVersion ? false
+, enableManpages ? false
+, enableSharedLibraries ? !enableManpages
+}:
+
+let
+  src = fetch "llvm" "0l9bf7kdwhlj0kq1hawpyxhna1062z3h7qcz2y8nfl9dz2qksy6s";
+
+  # Used when creating a version-suffixed symlink of libLLVM.dylib
+  shortVersion = with stdenv.lib;
+    concatStringsSep "." (take 2 (splitString "." release_version));
+in stdenv.mkDerivation (rec {
+  name = "llvm-${version}";
+
+  unpackPhase = ''
+    unpackFile ${src}
+    mv llvm-${version}* llvm
+    sourceRoot=$PWD/llvm
+    unpackFile ${compiler-rt_src}
+    mv compiler-rt-* $sourceRoot/projects/compiler-rt
+  '';
+
+  outputs = [ "out" ]
+    ++ stdenv.lib.optional enableSharedLibraries "lib";
+
+  nativeBuildInputs = [ cmake python ]
+    ++ stdenv.lib.optional enableManpages python.pkgs.sphinx;
+
+  buildInputs = [ libxml2 libffi ];
+
+  propagatedBuildInputs = [ ncurses zlib ];
+
+  # TSAN requires XPC on Darwin, which we have no public/free source files for. We can depend on the Apple frameworks
+  # to get it, but they're unfree. Since LLVM is rather central to the stdenv, we patch out TSAN support so that Hydra
+  # can build this. If we didn't do it, basically the entire nixpkgs on Darwin would have an unfree dependency and we'd
+  # get no binary cache for the entire platform. If you really find yourself wanting the TSAN, make this controllable by
+  # a flag and turn the flag off during the stdenv build.
+  postPatch = stdenv.lib.optionalString stdenv.isDarwin ''
+    substituteInPlace ./projects/compiler-rt/cmake/config-ix.cmake \
+      --replace 'set(COMPILER_RT_HAS_TSAN TRUE)' 'set(COMPILER_RT_HAS_TSAN FALSE)'
+
+    substituteInPlace cmake/modules/AddLLVM.cmake \
+      --replace 'set(_install_name_dir INSTALL_NAME_DIR "@rpath")' "set(_install_name_dir)" \
+      --replace 'set(_install_rpath "@loader_path/../lib" ''${extra_libdir})' ""
+  ''
+  # Patch llvm-config to return correct library path based on --link-{shared,static}.
+  + stdenv.lib.optionalString (enableSharedLibraries) ''
+    substitute '${./llvm-outputs.patch}' ./llvm-outputs.patch --subst-var lib
+    patch -p1 < ./llvm-outputs.patch
+  ''
+  + ''
+    (
+      cd projects/compiler-rt
+      patch -p1 < ${
+        fetchpatch {
+          name = "sigaltstack.patch"; # for glibc-2.26
+          url = https://github.com/llvm-mirror/compiler-rt/commit/8a5e425a68d.diff;
+          sha256 = "0h4y5vl74qaa7dl54b1fcyqalvlpd8zban2d1jxfkxpzyi7m8ifi";
+        }
+      }
+      substituteInPlace lib/esan/esan_sideline_linux.cpp \
+        --replace 'struct sigaltstack' 'stack_t'
+    )
+  '' + # Fix extra space printed in commandline help sometimes, "- help"
+  ''
+    patch -p1 -i ${./cmdline-help.patch}
+  '' + stdenv.lib.optionalString stdenv.isAarch64 ''
+    patch -p0 < ${../aarch64.patch}
+  '' + stdenv.lib.optionalString stdenv.hostPlatform.isMusl ''
+    patch -p1 -i ${../TLI-musl.patch}
+    patch -p1 -i ${../dynamiclibrary-musl.patch}
+    patch -p1 -i ${./sanitizers-nongnu.patch} -d projects/compiler-rt
+  '';
+
+  # hacky fix: created binaries need to be run before installation
+  preBuild = ''
+    mkdir -p $out/
+    ln -sv $PWD/lib $out
+  '';
+
+  cmakeFlags = with stdenv; [
+    "-DCMAKE_BUILD_TYPE=${if debugVersion then "Debug" else "Release"}"
+    "-DLLVM_INSTALL_UTILS=ON"  # Needed by rustc
+    "-DLLVM_BUILD_TESTS=ON"
+    "-DLLVM_ENABLE_FFI=ON"
+    "-DLLVM_ENABLE_RTTI=ON"
+    "-DCOMPILER_RT_INCLUDE_TESTS=OFF" # FIXME: requires clang source code
+
+    "-DLLVM_HOST_TRIPLE=${stdenv.hostPlatform.config}"
+    "-DLLVM_DEFAULT_TARGET_TRIPLE=${stdenv.hostPlatform.config}"
+    "-DTARGET_TRIPLE=${stdenv.hostPlatform.config}"
+  ]
+  ++ stdenv.lib.optional enableSharedLibraries
+    "-DLLVM_LINK_LLVM_DYLIB=ON"
+  ++ stdenv.lib.optionals enableManpages [
+    "-DLLVM_BUILD_DOCS=ON"
+    "-DLLVM_ENABLE_SPHINX=ON"
+    "-DSPHINX_OUTPUT_MAN=ON"
+    "-DSPHINX_OUTPUT_HTML=OFF"
+    "-DSPHINX_WARNINGS_AS_ERRORS=OFF"
+  ]
+  ++ stdenv.lib.optional (!isDarwin)
+    "-DLLVM_BINUTILS_INCDIR=${libbfd.dev}/include"
+  ++ stdenv.lib.optionals (isDarwin) [
+    "-DLLVM_ENABLE_LIBCXX=ON"
+    "-DCAN_TARGET_i386=false"
+  ];
+
+  postBuild = ''
+    rm -fR $out
+  '';
+
+  preCheck = ''
+    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PWD/lib
+  '';
+
+  postInstall = stdenv.lib.optionalString enableSharedLibraries ''
+    moveToOutput "lib/libLLVM-*" "$lib"
+    moveToOutput "lib/libLLVM${stdenv.hostPlatform.extensions.sharedLibrary}" "$lib"
+    substituteInPlace "$out/lib/cmake/llvm/LLVMExports-${if debugVersion then "debug" else "release"}.cmake" \
+      --replace "\''${_IMPORT_PREFIX}/lib/libLLVM-" "$lib/lib/libLLVM-"
+  ''
+  + stdenv.lib.optionalString (stdenv.isDarwin && enableSharedLibraries) ''
+    substituteInPlace "$out/lib/cmake/llvm/LLVMExports-${if debugVersion then "debug" else "release"}.cmake" \
+      --replace "\''${_IMPORT_PREFIX}/lib/libLLVM.dylib" "$lib/lib/libLLVM.dylib"
+    ln -s $lib/lib/libLLVM.dylib $lib/lib/libLLVM-${shortVersion}.dylib
+    ln -s $lib/lib/libLLVM.dylib $lib/lib/libLLVM-${release_version}.dylib
+  '';
+
+  doCheck = stdenv.isLinux && (!stdenv.isi686);
+
+  checkTarget = "check-all";
+
+  enableParallelBuilding = true;
+
+  passthru.src = src;
+
+  meta = {
+    description = "Collection of modular and reusable compiler and toolchain technologies";
+    homepage    = http://llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    maintainers = with stdenv.lib.maintainers; [ lovek323 raskin dtzWill ];
+    platforms   = stdenv.lib.platforms.all;
+  };
+} // stdenv.lib.optionalAttrs enableManpages {
+  name = "llvm-manpages-${version}";
+
+  buildPhase = ''
+    make docs-llvm-man
+  '';
+
+  propagatedBuildInputs = [ ];
+
+  installPhase = ''
+    make -C docs install
+  '';
+
+  outputs = [ "out" ];
+
+  doCheck = false;
+
+  meta.description = "man pages for LLVM ${version}";
+})
diff --git a/nixpkgs/pkgs/development/compilers/llvm/4/openmp.nix b/nixpkgs/pkgs/development/compilers/llvm/4/openmp.nix
new file mode 100644
index 000000000000..a8a6b3dfea87
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/4/openmp.nix
@@ -0,0 +1,25 @@
+{ stdenv
+, fetch
+, cmake
+, llvm
+, perl
+, version
+}:
+
+stdenv.mkDerivation {
+  name = "openmp-${version}";
+
+  src = fetch "openmp" "195dykamd39yhi5az7nqj3ksqhb3wq30l93jnfkxl0061qbknsgc";
+
+  nativeBuildInputs = [ cmake perl ];
+  buildInputs = [ llvm ];
+
+  enableParallelBuilding = true;
+
+  meta = {
+    description = "Components required to build an executable OpenMP program";
+    homepage    = http://openmp.llvm.org/;
+    license     = stdenv.lib.licenses.mit;
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/4/sanitizers-nongnu.patch b/nixpkgs/pkgs/development/compilers/llvm/4/sanitizers-nongnu.patch
new file mode 100644
index 000000000000..5bd858f8ae79
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/4/sanitizers-nongnu.patch
@@ -0,0 +1,368 @@
+From dac4d3912378069b44340204e5fc6237aa1baf94 Mon Sep 17 00:00:00 2001
+From: Matthias Maier <tamiko@43-1.org>
+Date: Fri, 5 May 2017 17:47:39 +0000
+Subject: [PATCH] Musl patches
+
+Ported to compiler-rt-sanitizers-4.0.0. Taken from
+
+  https://gist.githubusercontent.com/pwaller/2337f3290f12634cad3e3730cff0a6c1/raw/83c87a8585e2f9662494db5662e5361beb093c26/nongnu.patch
+---
+ lib/asan/asan_linux.cc                             |  4 +--
+ lib/interception/interception_linux.cc             |  2 +-
+ lib/interception/interception_linux.h              |  2 +-
+ lib/msan/msan_linux.cc                             |  2 +-
+ .../sanitizer_common_interceptors_ioctl.inc        |  4 +--
+ lib/sanitizer_common/sanitizer_common_syscalls.inc |  2 +-
+ lib/sanitizer_common/sanitizer_linux_libcdep.cc    | 12 +++----
+ lib/sanitizer_common/sanitizer_platform.h          |  7 ++++
+ .../sanitizer_platform_interceptors.h              |  2 +-
+ .../sanitizer_platform_limits_posix.cc             | 39 +++++++++++++---------
+ lib/tsan/rtl/tsan_platform_linux.cc                |  2 +-
+ 11 files changed, 46 insertions(+), 32 deletions(-)
+
+diff --git a/lib/asan/asan_linux.cc b/lib/asan/asan_linux.cc
+index c051573dd..e295f6004 100644
+--- a/lib/asan/asan_linux.cc
++++ b/lib/asan/asan_linux.cc
+@@ -39,7 +39,7 @@
+ #include <sys/link_elf.h>
+ #endif
+ 
+-#if SANITIZER_ANDROID || SANITIZER_FREEBSD
++#if SANITIZER_ANDROID || SANITIZER_FREEBSD || SANITIZER_NONGNU
+ #include <ucontext.h>
+ extern "C" void* _DYNAMIC;
+ #else
+@@ -80,7 +80,7 @@ void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
+   UNIMPLEMENTED();
+ }
+ 
+-#if SANITIZER_ANDROID
++#if SANITIZER_ANDROID || SANITIZER_NONGNU
+ // FIXME: should we do anything for Android?
+ void AsanCheckDynamicRTPrereqs() {}
+ void AsanCheckIncompatibleRT() {}
+diff --git a/lib/interception/interception_linux.cc b/lib/interception/interception_linux.cc
+index 6e908ac01..8f23d9adc 100644
+--- a/lib/interception/interception_linux.cc
++++ b/lib/interception/interception_linux.cc
+@@ -24,7 +24,7 @@ bool GetRealFunctionAddress(const char *func_name, uptr *func_addr,
+   return real == wrapper;
+ }
+ 
+-#if !defined(__ANDROID__)  // android does not have dlvsym
++#if !defined(__ANDROID__) && !SANITIZER_NONGNU  // android does not have dlvsym
+ void *GetFuncAddrVer(const char *func_name, const char *ver) {
+   return dlvsym(RTLD_NEXT, func_name, ver);
+ }
+diff --git a/lib/interception/interception_linux.h b/lib/interception/interception_linux.h
+index 27a66c882..3b559a303 100644
+--- a/lib/interception/interception_linux.h
++++ b/lib/interception/interception_linux.h
+@@ -34,7 +34,7 @@ void *GetFuncAddrVer(const char *func_name, const char *ver);
+       (::__interception::uptr) & (func),                                   \
+       (::__interception::uptr) & WRAP(func))
+ 
+-#if !defined(__ANDROID__)  // android does not have dlvsym
++#if !defined(__ANDROID__) && !SANITIZER_NONGNU  // android does not have dlvsym
+ #define INTERCEPT_FUNCTION_VER_LINUX_OR_FREEBSD(func, symver) \
+   (::__interception::real_##func = (func##_f)(                \
+        unsigned long)::__interception::GetFuncAddrVer(#func, symver))
+diff --git a/lib/msan/msan_linux.cc b/lib/msan/msan_linux.cc
+index 0a687f620..0852d97d7 100644
+--- a/lib/msan/msan_linux.cc
++++ b/lib/msan/msan_linux.cc
+@@ -13,7 +13,7 @@
+ //===----------------------------------------------------------------------===//
+ 
+ #include "sanitizer_common/sanitizer_platform.h"
+-#if SANITIZER_FREEBSD || SANITIZER_LINUX
++#if SANITIZER_FREEBSD || SANITIZER_LINUX && !SANITIZER_NONGNU
+ 
+ #include "msan.h"
+ #include "msan_thread.h"
+diff --git a/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc b/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
+index 4ed9afedf..64f584e93 100644
+--- a/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
++++ b/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
+@@ -100,7 +100,7 @@ static void ioctl_table_fill() {
+   _(SIOCGETVIFCNT, WRITE, struct_sioc_vif_req_sz);
+ #endif
+ 
+-#if SANITIZER_LINUX
++#if SANITIZER_LINUX && !SANITIZER_NONGNU
+   // Conflicting request ids.
+   // _(CDROMAUDIOBUFSIZ, NONE, 0);
+   // _(SNDCTL_TMR_CONTINUE, NONE, 0);
+@@ -361,7 +361,7 @@ static void ioctl_table_fill() {
+   _(VT_WAITACTIVE, NONE, 0);
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   // _(SIOCDEVPLIP, WRITE, struct_ifreq_sz); // the same as EQL_ENSLAVE
+   _(CYGETDEFTHRESH, WRITE, sizeof(int));
+   _(CYGETDEFTIMEOUT, WRITE, sizeof(int));
+diff --git a/lib/sanitizer_common/sanitizer_common_syscalls.inc b/lib/sanitizer_common/sanitizer_common_syscalls.inc
+index 469c8eb7e..24f87867d 100644
+--- a/lib/sanitizer_common/sanitizer_common_syscalls.inc
++++ b/lib/sanitizer_common/sanitizer_common_syscalls.inc
+@@ -2038,7 +2038,7 @@ POST_SYSCALL(setrlimit)(long res, long resource, void *rlim) {
+   }
+ }
+ 
+-#if !SANITIZER_ANDROID
++#if !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ PRE_SYSCALL(prlimit64)(long pid, long resource, const void *new_rlim,
+                        void *old_rlim) {
+   if (new_rlim) PRE_READ(new_rlim, struct_rlimit64_sz);
+diff --git a/lib/sanitizer_common/sanitizer_linux_libcdep.cc b/lib/sanitizer_common/sanitizer_linux_libcdep.cc
+index f99f0b594..3a773a94e 100644
+--- a/lib/sanitizer_common/sanitizer_linux_libcdep.cc
++++ b/lib/sanitizer_common/sanitizer_linux_libcdep.cc
+@@ -152,7 +152,7 @@ bool SanitizerGetThreadName(char *name, int max_len) {
+ #endif
+ }
+ 
+-#if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO
++#if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO && !SANITIZER_NONGNU
+ static uptr g_tls_size;
+ 
+ #ifdef __i386__
+@@ -180,11 +180,11 @@ void InitTlsSize() {
+ }
+ #else
+ void InitTlsSize() { }
+-#endif  // !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO
++#endif  // !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO && !SANITIZER_NONGNU
+ 
+ #if (defined(__x86_64__) || defined(__i386__) || defined(__mips__) \
+     || defined(__aarch64__) || defined(__powerpc64__) || defined(__s390__)) \
+-    && SANITIZER_LINUX && !SANITIZER_ANDROID
++    && SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ // sizeof(struct pthread) from glibc.
+ static atomic_uintptr_t kThreadDescriptorSize;
+ 
+@@ -338,7 +338,7 @@ uptr ThreadSelf() {
+ 
+ #if !SANITIZER_GO
+ static void GetTls(uptr *addr, uptr *size) {
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ # if defined(__x86_64__) || defined(__i386__) || defined(__s390__)
+   *addr = ThreadSelf();
+   *size = GetTlsSize();
+@@ -364,7 +364,7 @@ static void GetTls(uptr *addr, uptr *size) {
+     *addr = (uptr) dtv[2];
+     *size = (*addr == 0) ? 0 : ((uptr) segbase[0] - (uptr) dtv[2]);
+   }
+-#elif SANITIZER_ANDROID
++#elif SANITIZER_ANDROID || SANITIZER_NONGNU
+   *addr = 0;
+   *size = 0;
+ #else
+@@ -375,7 +375,7 @@ static void GetTls(uptr *addr, uptr *size) {
+ 
+ #if !SANITIZER_GO
+ uptr GetTlsSize() {
+-#if SANITIZER_FREEBSD || SANITIZER_ANDROID
++#if SANITIZER_FREEBSD || SANITIZER_ANDROID || SANITIZER_NONGNU
+   uptr addr, size;
+   GetTls(&addr, &size);
+   return size;
+diff --git a/lib/sanitizer_common/sanitizer_platform.h b/lib/sanitizer_common/sanitizer_platform.h
+index d9a8e8df1..fe01c5744 100644
+--- a/lib/sanitizer_common/sanitizer_platform.h
++++ b/lib/sanitizer_common/sanitizer_platform.h
+@@ -162,6 +162,13 @@
+ # define SANITIZER_PPC64V2 0
+ #endif
+ 
++
++#if defined(__linux__) && !defined(__GLIBC__)
++# define SANITIZER_NONGNU 1
++#else
++# define SANITIZER_NONGNU 0
++#endif
++
+ // By default we allow to use SizeClassAllocator64 on 64-bit platform.
+ // But in some cases (e.g. AArch64's 39-bit address space) SizeClassAllocator64
+ // does not work well and we need to fallback to SizeClassAllocator32.
+diff --git a/lib/sanitizer_common/sanitizer_platform_interceptors.h b/lib/sanitizer_common/sanitizer_platform_interceptors.h
+index 62875d11a..212e6e882 100644
+--- a/lib/sanitizer_common/sanitizer_platform_interceptors.h
++++ b/lib/sanitizer_common/sanitizer_platform_interceptors.h
+@@ -23,7 +23,7 @@
+ # define SI_NOT_WINDOWS 0
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ # define SI_LINUX_NOT_ANDROID 1
+ #else
+ # define SI_LINUX_NOT_ANDROID 0
+diff --git a/lib/sanitizer_common/sanitizer_platform_limits_posix.cc b/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
+index 683f019d7..fd4880962 100644
+--- a/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
++++ b/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
+@@ -14,6 +14,8 @@
+ 
+ #include "sanitizer_platform.h"
+ 
++#define _LINUX_SYSINFO_H
++
+ #if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_MAC
+ // Tests in this file assume that off_t-dependent data structures match the
+ // libc ABI. For example, struct dirent here is what readdir() function (as
+@@ -139,12 +141,14 @@ typedef struct user_fpregs elf_fpregset_t;
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+ #include <glob.h>
+-#include <obstack.h>
++#  if !SANITIZER_NONGNU
++#    include <obstack.h>
++#  endif
+ #include <mqueue.h>
+-#include <net/if_ppp.h>
+-#include <netax25/ax25.h>
+-#include <netipx/ipx.h>
+-#include <netrom/netrom.h>
++#include <linux/if_ppp.h>
++#include <linux/ax25.h>
++#include <linux/ipx.h>
++#include <linux/netrom.h>
+ #if HAVE_RPC_XDR_H
+ # include <rpc/xdr.h>
+ #elif HAVE_TIRPC_RPC_XDR_H
+@@ -160,7 +164,8 @@ typedef struct user_fpregs elf_fpregset_t;
+ # include <sys/procfs.h>
+ #endif
+ #include <sys/user.h>
+-#include <sys/ustat.h>
++// #include <sys/ustat.h>
++#include <sys/statfs.h>
+ #include <linux/cyclades.h>
+ #include <linux/if_eql.h>
+ #include <linux/if_plip.h>
+@@ -252,7 +257,7 @@ namespace __sanitizer {
+   unsigned struct_itimerspec_sz = sizeof(struct itimerspec);
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   unsigned struct_ustat_sz = sizeof(struct ustat);
+   unsigned struct_rlimit64_sz = sizeof(struct rlimit64);
+   unsigned struct_statvfs64_sz = sizeof(struct statvfs64);
+@@ -310,7 +315,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(ElfW(Phdr));
+ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+ #endif
+ 
+-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
++#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   int glob_nomatch = GLOB_NOMATCH;
+   int glob_altdirfunc = GLOB_ALTDIRFUNC;
+ #endif
+@@ -404,7 +409,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned struct_termios_sz = sizeof(struct termios);
+   unsigned struct_winsize_sz = sizeof(struct winsize);
+ 
+-#if SANITIZER_LINUX
++#if SANITIZER_LINUX && !SANITIZER_NONGNU
+   unsigned struct_arpreq_sz = sizeof(struct arpreq);
+   unsigned struct_cdrom_msf_sz = sizeof(struct cdrom_msf);
+   unsigned struct_cdrom_multisession_sz = sizeof(struct cdrom_multisession);
+@@ -454,7 +459,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned struct_vt_mode_sz = sizeof(struct vt_mode);
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   unsigned struct_ax25_parms_struct_sz = sizeof(struct ax25_parms_struct);
+   unsigned struct_cyclades_monitor_sz = sizeof(struct cyclades_monitor);
+ #if EV_VERSION > (0x010000)
+@@ -822,7 +827,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned IOCTL_VT_WAITACTIVE = VT_WAITACTIVE;
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   unsigned IOCTL_CYGETDEFTHRESH = CYGETDEFTHRESH;
+   unsigned IOCTL_CYGETDEFTIMEOUT = CYGETDEFTIMEOUT;
+   unsigned IOCTL_CYGETMON = CYGETMON;
+@@ -985,7 +990,7 @@ CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phdr);
+ CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phnum);
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
++#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ CHECK_TYPE_SIZE(glob_t);
+ CHECK_SIZE_AND_OFFSET(glob_t, gl_pathc);
+ CHECK_SIZE_AND_OFFSET(glob_t, gl_pathv);
+@@ -1019,6 +1024,7 @@ CHECK_TYPE_SIZE(iovec);
+ CHECK_SIZE_AND_OFFSET(iovec, iov_base);
+ CHECK_SIZE_AND_OFFSET(iovec, iov_len);
+ 
++#if !SANITIZER_NONGNU
+ CHECK_TYPE_SIZE(msghdr);
+ CHECK_SIZE_AND_OFFSET(msghdr, msg_name);
+ CHECK_SIZE_AND_OFFSET(msghdr, msg_namelen);
+@@ -1032,6 +1038,7 @@ CHECK_TYPE_SIZE(cmsghdr);
+ CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_len);
+ CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_level);
+ CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_type);
++#endif
+ 
+ COMPILER_CHECK(sizeof(__sanitizer_dirent) <= sizeof(dirent));
+ CHECK_SIZE_AND_OFFSET(dirent, d_ino);
+@@ -1134,7 +1141,7 @@ CHECK_SIZE_AND_OFFSET(mntent, mnt_passno);
+ 
+ CHECK_TYPE_SIZE(ether_addr);
+ 
+-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
++#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ CHECK_TYPE_SIZE(ipc_perm);
+ # if SANITIZER_FREEBSD
+ CHECK_SIZE_AND_OFFSET(ipc_perm, key);
+@@ -1195,7 +1202,7 @@ CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_dstaddr);
+ CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_data);
+ #endif
+ 
+-#if SANITIZER_LINUX
++#if SANITIZER_LINUX && !SANITIZER_NONGNU
+ COMPILER_CHECK(sizeof(__sanitizer_mallinfo) == sizeof(struct mallinfo));
+ #endif
+ 
+@@ -1245,7 +1252,7 @@ COMPILER_CHECK(__sanitizer_XDR_DECODE == XDR_DECODE);
+ COMPILER_CHECK(__sanitizer_XDR_FREE == XDR_FREE);
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ COMPILER_CHECK(sizeof(__sanitizer_FILE) <= sizeof(FILE));
+ CHECK_SIZE_AND_OFFSET(FILE, _flags);
+ CHECK_SIZE_AND_OFFSET(FILE, _IO_read_ptr);
+@@ -1264,7 +1271,7 @@ CHECK_SIZE_AND_OFFSET(FILE, _chain);
+ CHECK_SIZE_AND_OFFSET(FILE, _fileno);
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ COMPILER_CHECK(sizeof(__sanitizer__obstack_chunk) <= sizeof(_obstack_chunk));
+ CHECK_SIZE_AND_OFFSET(_obstack_chunk, limit);
+ CHECK_SIZE_AND_OFFSET(_obstack_chunk, prev);
+diff --git a/lib/tsan/rtl/tsan_platform_linux.cc b/lib/tsan/rtl/tsan_platform_linux.cc
+index 3313288a7..103c7b6b9 100644
+--- a/lib/tsan/rtl/tsan_platform_linux.cc
++++ b/lib/tsan/rtl/tsan_platform_linux.cc
+@@ -287,7 +287,7 @@ void InitializePlatform() {
+ // This is required to properly "close" the fds, because we do not see internal
+ // closes within glibc. The code is a pure hack.
+ int ExtractResolvFDs(void *state, int *fds, int nfd) {
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   int cnt = 0;
+   __res_state *statp = (__res_state*)state;
+   for (int i = 0; i < MAXNS && cnt < nfd; i++) {
+-- 
+2.16.2
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/5/clang/default.nix b/nixpkgs/pkgs/development/compilers/llvm/5/clang/default.nix
new file mode 100644
index 000000000000..5fd0271f0261
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/5/clang/default.nix
@@ -0,0 +1,106 @@
+{ stdenv, fetch, cmake, libxml2, llvm, version, clang-tools-extra_src, python
+, fixDarwinDylibNames
+, enableManpages ? false
+}:
+
+let
+  gcc = if stdenv.cc.isGNU then stdenv.cc.cc else stdenv.cc.cc.gcc;
+  self = stdenv.mkDerivation ({
+    name = "clang-${version}";
+
+    unpackPhase = ''
+      unpackFile ${fetch "cfe" "0018520c4qxf5hgjdqgpz2dgl3faf4gsz87fdlb8zdmx99rfk77s"}
+      mv cfe-${version}* clang
+      sourceRoot=$PWD/clang
+      unpackFile ${clang-tools-extra_src}
+      mv clang-tools-extra-* $sourceRoot/tools/extra
+    '';
+
+    nativeBuildInputs = [ cmake python ]
+      ++ stdenv.lib.optional enableManpages python.pkgs.sphinx;
+
+    buildInputs = [ libxml2 llvm ]
+      ++ stdenv.lib.optional stdenv.isDarwin fixDarwinDylibNames;
+
+    cmakeFlags = [
+      "-DCMAKE_CXX_FLAGS=-std=c++11"
+    ] ++ stdenv.lib.optionals enableManpages [
+      "-DCLANG_INCLUDE_DOCS=ON"
+      "-DLLVM_ENABLE_SPHINX=ON"
+      "-DSPHINX_OUTPUT_MAN=ON"
+      "-DSPHINX_OUTPUT_HTML=OFF"
+      "-DSPHINX_WARNINGS_AS_ERRORS=OFF"
+    ];
+
+    patches = [ ./purity.patch ];
+
+    postPatch = ''
+      sed -i -e 's/DriverArgs.hasArg(options::OPT_nostdlibinc)/true/' \
+             -e 's/Args.hasArg(options::OPT_nostdlibinc)/true/' \
+             lib/Driver/ToolChains/*.cpp
+
+      # Patch for standalone doc building
+      sed -i '1s,^,find_package(Sphinx REQUIRED)\n,' docs/CMakeLists.txt
+    '' + stdenv.lib.optionalString stdenv.hostPlatform.isMusl ''
+      sed -i -e 's/lgcc_s/lgcc_eh/' lib/Driver/ToolChains/*.cpp
+    '';
+
+    outputs = [ "out" "lib" "python" ];
+
+    # Clang expects to find LLVMgold in its own prefix
+    postInstall = ''
+      if [ -e ${llvm}/lib/LLVMgold.so ]; then
+        ln -sv ${llvm}/lib/LLVMgold.so $out/lib
+      fi
+
+      ln -sv $out/bin/clang $out/bin/cpp
+
+      # Move libclang to 'lib' output
+      moveToOutput "lib/libclang.*" "$lib"
+      substituteInPlace $out/lib/cmake/clang/ClangTargets-release.cmake \
+          --replace "\''${_IMPORT_PREFIX}/lib/libclang." "$lib/lib/libclang."
+
+      mkdir -p $python/bin $python/share/clang/
+      mv $out/bin/{git-clang-format,scan-view} $python/bin
+      if [ -e $out/bin/set-xcode-analyzer ]; then
+        mv $out/bin/set-xcode-analyzer $python/bin
+      fi
+      mv $out/share/clang/*.py $python/share/clang
+      rm $out/bin/c-index-test
+    '';
+
+    enableParallelBuilding = true;
+
+    passthru = {
+      isClang = true;
+      inherit llvm;
+    } // stdenv.lib.optionalAttrs stdenv.isLinux {
+      inherit gcc;
+    };
+
+    meta = {
+      description = "A c, c++, objective-c, and objective-c++ frontend for the llvm compiler";
+      homepage    = http://llvm.org/;
+      license     = stdenv.lib.licenses.ncsa;
+      platforms   = stdenv.lib.platforms.all;
+    };
+  } // stdenv.lib.optionalAttrs enableManpages {
+    name = "clang-manpages-${version}";
+
+    buildPhase = ''
+      make docs-clang-man
+    '';
+
+    installPhase = ''
+      mkdir -p $out/share/man/man1
+      # Manually install clang manpage
+      cp docs/man/*.1 $out/share/man/man1/
+    '';
+
+    outputs = [ "out" ];
+
+    doCheck = false;
+
+    meta.description = "man page for Clang ${version}";
+  });
+in self
diff --git a/nixpkgs/pkgs/development/compilers/llvm/5/clang/purity.patch b/nixpkgs/pkgs/development/compilers/llvm/5/clang/purity.patch
new file mode 100644
index 000000000000..b30d0d0b5d5b
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/5/clang/purity.patch
@@ -0,0 +1,30 @@
+From 4add81bba40dcec62c4ea4481be8e35ac53e89d8 Mon Sep 17 00:00:00 2001
+From: Will Dietz <w@wdtz.org>
+Date: Thu, 18 May 2017 11:56:12 -0500
+Subject: [PATCH] "purity" patch for 5.0
+
+---
+ lib/Driver/ToolChains/Gnu.cpp | 7 -------
+ 1 file changed, 7 deletions(-)
+
+diff --git a/lib/Driver/ToolChains/Gnu.cpp b/lib/Driver/ToolChains/Gnu.cpp
+index fe3c0191bb..c6a482bece 100644
+--- a/lib/Driver/ToolChains/Gnu.cpp
++++ b/lib/Driver/ToolChains/Gnu.cpp
+@@ -494,13 +494,6 @@ void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
+   if (!Args.hasArg(options::OPT_static)) {
+     if (Args.hasArg(options::OPT_rdynamic))
+       CmdArgs.push_back("-export-dynamic");
+-
+-    if (!Args.hasArg(options::OPT_shared)) {
+-      const std::string Loader =
+-          D.DyldPrefix + ToolChain.getDynamicLinker(Args);
+-      CmdArgs.push_back("-dynamic-linker");
+-      CmdArgs.push_back(Args.MakeArgString(Loader));
+-    }
+   }
+ 
+   CmdArgs.push_back("-o");
+-- 
+2.11.0
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/5/compiler-rt-codesign.patch b/nixpkgs/pkgs/development/compilers/llvm/5/compiler-rt-codesign.patch
new file mode 100644
index 000000000000..8f4c76bca1eb
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/5/compiler-rt-codesign.patch
@@ -0,0 +1,155 @@
+From 3dec5f3475a26aeb4678627795c4b67c6b7b4785 Mon Sep 17 00:00:00 2001
+From: Will Dietz <w@wdtz.org>
+Date: Tue, 19 Sep 2017 13:13:06 -0500
+Subject: [PATCH] remove codesign use on Apple, disable ios sim testing that
+ needs it
+
+---
+ cmake/Modules/AddCompilerRT.cmake |  8 ------
+ test/asan/CMakeLists.txt          | 52 ---------------------------------------
+ test/tsan/CMakeLists.txt          | 47 -----------------------------------
+ 3 files changed, 107 deletions(-)
+
+diff --git a/cmake/Modules/AddCompilerRT.cmake b/cmake/Modules/AddCompilerRT.cmake
+index bc5fb9ff7..b64eb4246 100644
+--- a/cmake/Modules/AddCompilerRT.cmake
++++ b/cmake/Modules/AddCompilerRT.cmake
+@@ -210,14 +210,6 @@ function(add_compiler_rt_runtime name type)
+         set_target_properties(${libname} PROPERTIES IMPORT_PREFIX "")
+         set_target_properties(${libname} PROPERTIES IMPORT_SUFFIX ".lib")
+       endif()
+-      if(APPLE)
+-        # Ad-hoc sign the dylibs
+-        add_custom_command(TARGET ${libname}
+-          POST_BUILD  
+-          COMMAND codesign --sign - $<TARGET_FILE:${libname}>
+-          WORKING_DIRECTORY ${COMPILER_RT_LIBRARY_OUTPUT_DIR}
+-        )
+-      endif()
+     endif()
+     install(TARGETS ${libname}
+       ARCHIVE DESTINATION ${COMPILER_RT_LIBRARY_INSTALL_DIR}
+diff --git a/test/asan/CMakeLists.txt b/test/asan/CMakeLists.txt
+index 8bfc15b5c..f23d0f71a 100644
+--- a/test/asan/CMakeLists.txt
++++ b/test/asan/CMakeLists.txt
+@@ -83,58 +83,6 @@ foreach(arch ${ASAN_TEST_ARCH})
+   endif()
+ endforeach()
+ 
+-# iOS and iOS simulator test suites
+-# These are not added into "check-all", in order to run these tests, use
+-# "check-asan-iossim-x86_64" and similar. They also require that an extra env
+-# variable to select which iOS device or simulator to use, e.g.:
+-# SANITIZER_IOSSIM_TEST_DEVICE_IDENTIFIER="iPhone 6"
+-if(APPLE)
+-  set(EXCLUDE_FROM_ALL ON)
+-
+-  set(ASAN_TEST_TARGET_CC ${COMPILER_RT_TEST_COMPILER})
+-  set(ASAN_TEST_IOS "1")
+-  pythonize_bool(ASAN_TEST_IOS)
+-  set(ASAN_TEST_DYNAMIC True)
+-
+-  foreach(arch ${DARWIN_iossim_ARCHS})
+-    set(ASAN_TEST_IOSSIM "1")
+-    pythonize_bool(ASAN_TEST_IOSSIM)
+-    set(ASAN_TEST_TARGET_ARCH ${arch})
+-    set(ASAN_TEST_TARGET_CFLAGS "-arch ${arch} -isysroot ${DARWIN_iossim_SYSROOT} ${COMPILER_RT_TEST_COMPILER_CFLAGS}")
+-    set(ASAN_TEST_CONFIG_SUFFIX "-${arch}-iossim")
+-    get_bits_for_arch(${arch} ASAN_TEST_BITS)
+-    string(TOUPPER ${arch} ARCH_UPPER_CASE)
+-    set(CONFIG_NAME "IOSSim${ARCH_UPPER_CASE}Config")
+-    configure_lit_site_cfg(
+-      ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in
+-      ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/lit.site.cfg
+-      )
+-    add_lit_testsuite(check-asan-iossim-${arch} "AddressSanitizer iOS Simulator ${arch} tests"
+-      ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/
+-      DEPENDS ${ASAN_TEST_DEPS})
+-  endforeach()
+-
+-  foreach (arch ${DARWIN_ios_ARCHS})
+-    set(ASAN_TEST_IOSSIM "0")
+-    pythonize_bool(ASAN_TEST_IOSSIM)
+-    set(ASAN_TEST_TARGET_ARCH ${arch})
+-    set(ASAN_TEST_TARGET_CFLAGS "-arch ${arch} -isysroot ${DARWIN_ios_SYSROOT} ${COMPILER_RT_TEST_COMPILER_CFLAGS}")
+-    set(ASAN_TEST_CONFIG_SUFFIX "-${arch}-ios")
+-    get_bits_for_arch(${arch} ASAN_TEST_BITS)
+-    string(TOUPPER ${arch} ARCH_UPPER_CASE)
+-    set(CONFIG_NAME "IOS${ARCH_UPPER_CASE}Config")
+-    configure_lit_site_cfg(
+-      ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in
+-      ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/lit.site.cfg
+-      )
+-    add_lit_testsuite(check-asan-ios-${arch} "AddressSanitizer iOS ${arch} tests"
+-      ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/
+-      DEPENDS ${ASAN_TEST_DEPS})
+-  endforeach()
+-
+-  set(EXCLUDE_FROM_ALL OFF)
+-endif()
+-
+ # Add unit tests.
+ if(COMPILER_RT_INCLUDE_TESTS)
+   set(ASAN_TEST_DYNAMIC False)
+diff --git a/test/tsan/CMakeLists.txt b/test/tsan/CMakeLists.txt
+index a68908612..cde0accb5 100644
+--- a/test/tsan/CMakeLists.txt
++++ b/test/tsan/CMakeLists.txt
+@@ -42,53 +42,6 @@ foreach(arch ${TSAN_TEST_ARCH})
+   list(APPEND TSAN_TESTSUITES ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME})
+ endforeach()
+ 
+-# iOS and iOS simulator test suites
+-# These are not added into "check-all", in order to run these tests, use
+-# "check-tsan-iossim-x86_64" and similar. They also require an extra environment
+-# variable to select which iOS device or simulator to use, e.g.:
+-# SANITIZER_IOSSIM_TEST_DEVICE_IDENTIFIER="iPhone 6"
+-if(APPLE)
+-  set(EXCLUDE_FROM_ALL ON)
+-
+-  set(TSAN_TEST_TARGET_CC ${COMPILER_RT_TEST_COMPILER})
+-  set(TSAN_TEST_IOS "1")
+-  pythonize_bool(TSAN_TEST_IOS)
+-
+-  set(arch "x86_64")
+-  set(TSAN_TEST_IOSSIM "1")
+-  pythonize_bool(TSAN_TEST_IOSSIM)
+-  set(TSAN_TEST_TARGET_ARCH ${arch})
+-  set(TSAN_TEST_TARGET_CFLAGS "-arch ${arch} -isysroot ${DARWIN_iossim_SYSROOT} ${COMPILER_RT_TEST_COMPILER_CFLAGS}")
+-  set(TSAN_TEST_CONFIG_SUFFIX "-${arch}-iossim")
+-  string(TOUPPER ${arch} ARCH_UPPER_CASE)
+-  set(CONFIG_NAME "IOSSim${ARCH_UPPER_CASE}Config")
+-  configure_lit_site_cfg(
+-    ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in
+-    ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/lit.site.cfg
+-    )
+-  add_lit_testsuite(check-tsan-iossim-${arch} "ThreadSanitizer iOS Simulator ${arch} tests"
+-    ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/
+-    DEPENDS ${TSAN_TEST_DEPS})
+-
+-  set(arch "arm64")
+-  set(TSAN_TEST_IOSSIM "0")
+-  pythonize_bool(TSAN_TEST_IOSSIM)
+-  set(TSAN_TEST_TARGET_ARCH ${arch})
+-  set(TSAN_TEST_TARGET_CFLAGS "-arch ${arch} -isysroot ${DARWIN_ios_SYSROOT} ${COMPILER_RT_TEST_COMPILER_CFLAGS}")
+-  set(TSAN_TEST_CONFIG_SUFFIX "-${arch}-ios")
+-  string(TOUPPER ${arch} ARCH_UPPER_CASE)
+-  set(CONFIG_NAME "IOS${ARCH_UPPER_CASE}Config")
+-  configure_lit_site_cfg(
+-    ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in
+-    ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/lit.site.cfg
+-    )
+-  add_lit_testsuite(check-tsan-ios-${arch} "ThreadSanitizer iOS Simulator ${arch} tests"
+-    ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/
+-    DEPENDS ${TSAN_TEST_DEPS})
+-
+-  set(EXCLUDE_FROM_ALL OFF)
+-endif()
+-
+ if(COMPILER_RT_INCLUDE_TESTS)
+   configure_lit_site_cfg(
+     ${CMAKE_CURRENT_SOURCE_DIR}/Unit/lit.site.cfg.in
+-- 
+2.14.1
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/5/compiler-rt.nix b/nixpkgs/pkgs/development/compilers/llvm/5/compiler-rt.nix
new file mode 100644
index 000000000000..19833e4d3d4a
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/5/compiler-rt.nix
@@ -0,0 +1,37 @@
+{ stdenv, version, fetch, cmake, python, llvm, libcxxabi }:
+with stdenv.lib;
+stdenv.mkDerivation rec {
+  name = "compiler-rt-${version}";
+  inherit version;
+  src = fetch "compiler-rt" "0ipd4jdxpczgr2w6lzrabymz6dhzj69ywmyybjjc1q397zgrvziy";
+
+  nativeBuildInputs = [ cmake python llvm ];
+  buildInputs = stdenv.lib.optional stdenv.hostPlatform.isDarwin libcxxabi;
+
+  configureFlags = [
+    "-DCOMPILER_RT_DEFAULT_TARGET_ONLY=ON"
+  ];
+
+  outputs = [ "out" "dev" ];
+
+  patches = [
+    ./compiler-rt-codesign.patch # Revert compiler-rt commit that makes codesign mandatory
+  ] ++ optional stdenv.hostPlatform.isMusl ./sanitizers-nongnu.patch;
+
+  # TSAN requires XPC on Darwin, which we have no public/free source files for. We can depend on the Apple frameworks
+  # to get it, but they're unfree. Since LLVM is rather central to the stdenv, we patch out TSAN support so that Hydra
+  # can build this. If we didn't do it, basically the entire nixpkgs on Darwin would have an unfree dependency and we'd
+  # get no binary cache for the entire platform. If you really find yourself wanting the TSAN, make this controllable by
+  # a flag and turn the flag off during the stdenv build.
+  postPatch = stdenv.lib.optionalString stdenv.isDarwin ''
+    substituteInPlace cmake/config-ix.cmake \
+      --replace 'set(COMPILER_RT_HAS_TSAN TRUE)' 'set(COMPILER_RT_HAS_TSAN FALSE)'
+  '';
+
+  # Hack around weird upsream RPATH bug
+  postInstall = stdenv.lib.optionalString stdenv.isDarwin ''
+    ln -s "$out/lib"/*/* "$out/lib"
+  '';
+
+  enableParallelBuilding = true;
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/5/default.nix b/nixpkgs/pkgs/development/compilers/llvm/5/default.nix
new file mode 100644
index 000000000000..6807240df81e
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/5/default.nix
@@ -0,0 +1,93 @@
+{ lowPrio, newScope, pkgs, stdenv, cmake, libstdcxxHook
+, libxml2, python, isl, fetchurl, overrideCC, wrapCCWith
+, buildLlvmTools # tools, but from the previous stage, for cross
+, targetLlvmLibraries # libraries, but from the next stage, for cross
+}:
+
+let
+  release_version = "5.0.2";
+  version = release_version; # differentiating these is important for rc's
+
+  fetch = name: sha256: fetchurl {
+    url = "https://releases.llvm.org/${release_version}/${name}-${version}.src.tar.xz";
+    inherit sha256;
+  };
+
+  clang-tools-extra_src = fetch "clang-tools-extra" "018b3fiwah8f8br5i26qmzh6sjvzchpn358sn8v079m49f2jldm3";
+
+  tools = stdenv.lib.makeExtensible (tools: let
+    callPackage = newScope (tools // { inherit stdenv cmake libxml2 python isl release_version version fetch; });
+    mkExtraBuildCommands = cc: ''
+      rsrc="$out/resource-root"
+      mkdir "$rsrc"
+      ln -s "${cc}/lib/clang/${release_version}/include" "$rsrc"
+      ln -s "${targetLlvmLibraries.compiler-rt.out}/lib" "$rsrc/lib"
+      echo "-resource-dir=$rsrc" >> $out/nix-support/cc-cflags
+    '' + stdenv.lib.optionalString stdenv.targetPlatform.isLinux ''
+      echo "--gcc-toolchain=${tools.clang-unwrapped.gcc}" >> $out/nix-support/cc-cflags
+    '';
+  in {
+
+    llvm = callPackage ./llvm.nix { };
+
+    clang-unwrapped = callPackage ./clang {
+      inherit clang-tools-extra_src;
+    };
+
+    llvm-manpages = lowPrio (tools.llvm.override {
+      enableManpages = true;
+      python = pkgs.python;  # don't use python-boot
+    });
+
+    clang-manpages = lowPrio (tools.clang-unwrapped.override {
+      enableManpages = true;
+      python = pkgs.python;  # don't use python-boot
+    });
+
+    libclang = tools.clang-unwrapped.lib;
+
+    clang = if stdenv.cc.isGNU then tools.libstdcxxClang else tools.libcxxClang;
+
+    libstdcxxClang = wrapCCWith rec {
+      cc = tools.clang-unwrapped;
+      extraPackages = [
+        libstdcxxHook
+        targetLlvmLibraries.compiler-rt
+      ];
+      extraBuildCommands = mkExtraBuildCommands cc;
+    };
+
+    libcxxClang = wrapCCWith rec {
+      cc = tools.clang-unwrapped;
+      libcxx = targetLlvmLibraries.libcxx;
+      extraPackages = [
+        targetLlvmLibraries.libcxx
+        targetLlvmLibraries.libcxxabi
+        targetLlvmLibraries.compiler-rt
+      ];
+      extraBuildCommands = mkExtraBuildCommands cc;
+    };
+
+    lld = callPackage ./lld.nix {};
+
+    lldb = callPackage ./lldb.nix {};
+  });
+
+  libraries = stdenv.lib.makeExtensible (libraries: let
+    callPackage = newScope (libraries // buildLlvmTools // { inherit stdenv cmake libxml2 python isl release_version version fetch; });
+  in {
+
+    compiler-rt = callPackage ./compiler-rt.nix {};
+
+    stdenv = overrideCC stdenv buildLlvmTools.clang;
+
+    libcxxStdenv = overrideCC stdenv buildLlvmTools.libcxxClang;
+
+    libcxx = callPackage ./libc++ {};
+
+    libcxxabi = callPackage ./libc++abi.nix {};
+
+    openmp = callPackage ./openmp.nix {};
+  });
+
+in { inherit tools libraries; } // libraries // tools
diff --git a/nixpkgs/pkgs/development/compilers/llvm/5/libc++/default.nix b/nixpkgs/pkgs/development/compilers/llvm/5/libc++/default.nix
new file mode 100644
index 000000000000..b182f1250e72
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/5/libc++/default.nix
@@ -0,0 +1,52 @@
+{ lib, stdenv, fetch, cmake, python, libcxxabi, fixDarwinDylibNames, version }:
+
+stdenv.mkDerivation rec {
+  name = "libc++-${version}";
+
+  src = fetch "libcxx" "1672aaf95fgy4xsfra8pw24f6r93zwzpan1033hkcm8p2glqipvf";
+
+  postUnpack = ''
+    unpackFile ${libcxxabi.src}
+    export LIBCXXABI_INCLUDE_DIR="$PWD/$(ls -d libcxxabi-${version}*)/include"
+  '';
+
+  patches = stdenv.lib.optionals stdenv.hostPlatform.isMusl [
+    ../../libcxx-0001-musl-hacks.patch
+  ];
+
+  prePatch = ''
+    substituteInPlace lib/CMakeLists.txt --replace "/usr/lib/libc++" "\''${LIBCXX_LIBCXXABI_LIB_PATH}/libc++"
+  '';
+
+  preConfigure = ''
+    # Get headers from the cxxabi source so we can see private headers not installed by the cxxabi package
+    cmakeFlagsArray=($cmakeFlagsArray -DLIBCXX_CXX_ABI_INCLUDE_PATHS="$LIBCXXABI_INCLUDE_DIR")
+  '' + lib.optionalString stdenv.hostPlatform.isMusl ''
+    patchShebangs utils/cat_files.py
+  '';
+  nativeBuildInputs = [ cmake ] ++ stdenv.lib.optional stdenv.hostPlatform.isMusl python;
+
+  buildInputs = [ libcxxabi ] ++ lib.optional stdenv.isDarwin fixDarwinDylibNames;
+
+  cmakeFlags = [
+    "-DLIBCXX_LIBCXXABI_LIB_PATH=${libcxxabi}/lib"
+    "-DLIBCXX_LIBCPPABI_VERSION=2"
+    "-DLIBCXX_CXX_ABI=libcxxabi"
+  ] ++ stdenv.lib.optional stdenv.hostPlatform.isMusl "-DLIBCXX_HAS_MUSL_LIBC=1";
+
+  enableParallelBuilding = true;
+
+  linkCxxAbi = stdenv.isLinux;
+
+  setupHooks = [
+    ../../../../../build-support/setup-hooks/role.bash
+    ./setup-hook.sh
+  ];
+
+  meta = {
+    homepage = http://libcxx.llvm.org/;
+    description = "A new implementation of the C++ standard library, targeting C++11";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/5/libc++/setup-hook.sh b/nixpkgs/pkgs/development/compilers/llvm/5/libc++/setup-hook.sh
new file mode 100644
index 000000000000..6611259165ae
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/5/libc++/setup-hook.sh
@@ -0,0 +1,6 @@
+# See pkgs/build-support/setup-hooks/role.bash
+getHostRole
+
+linkCxxAbi="@linkCxxAbi@"
+export NIX_${role_pre}CXXSTDLIB_COMPILE+=" -isystem @out@/include/c++/v1"
+export NIX_${role_pre}CXXSTDLIB_LINK=" -stdlib=libc++${linkCxxAbi:+" -lc++abi"}"
diff --git a/nixpkgs/pkgs/development/compilers/llvm/5/libc++abi.nix b/nixpkgs/pkgs/development/compilers/llvm/5/libc++abi.nix
new file mode 100644
index 000000000000..227ecbeda194
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/5/libc++abi.nix
@@ -0,0 +1,50 @@
+{ stdenv, cmake, fetch, libcxx, libunwind, llvm, version }:
+
+stdenv.mkDerivation {
+  name = "libc++abi-${version}";
+
+  src = fetch "libcxxabi" "12lp799rskr4fc2xr64qn4jfkjnfd8b1aymvsxyn4k9ar7r9pgqv";
+
+  nativeBuildInputs = [ cmake ];
+  buildInputs = stdenv.lib.optional (!stdenv.isDarwin && !stdenv.isFreeBSD) libunwind;
+
+  postUnpack = ''
+    unpackFile ${libcxx.src}
+    unpackFile ${llvm.src}
+    export cmakeFlags="-DLLVM_PATH=$PWD/$(ls -d llvm-*) -DLIBCXXABI_LIBCXX_PATH=$PWD/$(ls -d libcxx-*)"
+  '' + stdenv.lib.optionalString stdenv.isDarwin ''
+    export TRIPLE=x86_64-apple-darwin
+  '' + stdenv.lib.optionalString stdenv.hostPlatform.isMusl ''
+    patch -p1 -d $(ls -d libcxx-*) -i ${../libcxx-0001-musl-hacks.patch}
+  '';
+
+  installPhase = if stdenv.isDarwin
+    then ''
+      for file in lib/*.dylib; do
+        # this should be done in CMake, but having trouble figuring out
+        # the magic combination of necessary CMake variables
+        # if you fancy a try, take a look at
+        # http://www.cmake.org/Wiki/CMake_RPATH_handling
+        install_name_tool -id $out/$file $file
+      done
+      make install
+      install -d 755 $out/include
+      install -m 644 ../include/*.h $out/include
+    ''
+    else ''
+      install -d -m 755 $out/include $out/lib
+      install -m 644 lib/libc++abi.a $out/lib
+      install -m 644 lib/libc++abi.so.1.0 $out/lib
+      install -m 644 ../include/cxxabi.h $out/include
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so.1
+    '';
+
+  meta = {
+    homepage = http://libcxxabi.llvm.org/;
+    description = "A new implementation of low level support for a standard C++ library";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    maintainers = with stdenv.lib.maintainers; [ vlstill ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/5/lld.nix b/nixpkgs/pkgs/development/compilers/llvm/5/lld.nix
new file mode 100644
index 000000000000..9a47435cf140
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/5/lld.nix
@@ -0,0 +1,31 @@
+{ stdenv
+, fetch
+, cmake
+, llvm
+, version
+}:
+
+stdenv.mkDerivation {
+  name = "lld-${version}";
+
+  src = fetch "lld" "1ah75rjly6747jk1zbwca3z0svr9b09ylgxd4x9ns721xir6sia6";
+
+  nativeBuildInputs = [ cmake ];
+  buildInputs = [ llvm ];
+
+  outputs = [ "out" "dev" ];
+
+  enableParallelBuilding = true;
+
+  postInstall = ''
+    moveToOutput include "$dev"
+    moveToOutput lib "$dev"
+  '';
+
+  meta = {
+    description = "The LLVM Linker";
+    homepage    = http://lld.llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/5/lldb.nix b/nixpkgs/pkgs/development/compilers/llvm/5/lldb.nix
new file mode 100644
index 000000000000..7be9a7e47b74
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/5/lldb.nix
@@ -0,0 +1,56 @@
+{ stdenv
+, fetch
+, cmake
+, zlib
+, ncurses
+, swig
+, which
+, libedit
+, libxml2
+, llvm
+, clang-unwrapped
+, python
+, version
+, darwin
+}:
+
+stdenv.mkDerivation {
+  name = "lldb-${version}";
+
+  src = fetch "lldb" "05j2a63yzln43852nng8a7y47spzlyr1cvdmgmbxgd29c8r0bfkq";
+
+  postPatch = ''
+    # Fix up various paths that assume llvm and clang are installed in the same place
+    sed -i 's,".*ClangConfig.cmake","${clang-unwrapped}/lib/cmake/clang/ClangConfig.cmake",' \
+      cmake/modules/LLDBStandalone.cmake
+    sed -i 's,".*tools/clang/include","${clang-unwrapped}/include",' \
+      cmake/modules/LLDBStandalone.cmake
+    sed -i 's,"$.LLVM_LIBRARY_DIR.",${llvm}/lib ${clang-unwrapped}/lib,' \
+      cmake/modules/LLDBStandalone.cmake
+  '';
+
+  nativeBuildInputs = [ cmake python which swig ];
+  buildInputs = [ ncurses zlib libedit libxml2 llvm ]
+    ++ stdenv.lib.optionals stdenv.isDarwin [ darwin.libobjc darwin.apple_sdk.libs.xpc darwin.apple_sdk.frameworks.Foundation darwin.bootstrap_cmds darwin.apple_sdk.frameworks.Carbon darwin.apple_sdk.frameworks.Cocoa darwin.cf-private ];
+
+  CXXFLAGS = "-fno-rtti";
+  hardeningDisable = [ "format" ];
+
+  cmakeFlags = [
+    "-DLLDB_CODESIGN_IDENTITY=" # codesigning makes nondeterministic
+  ];
+
+  enableParallelBuilding = true;
+
+  postInstall = ''
+    mkdir -p $out/share/man/man1
+    cp ../docs/lldb.1 $out/share/man/man1/
+  '';
+
+  meta = with stdenv.lib; {
+    description = "A next-generation high-performance debugger";
+    homepage    = http://llvm.org/;
+    license     = licenses.ncsa;
+    platforms   = platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/5/llvm-outputs.patch b/nixpkgs/pkgs/development/compilers/llvm/5/llvm-outputs.patch
new file mode 100644
index 000000000000..40096fa3497f
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/5/llvm-outputs.patch
@@ -0,0 +1,26 @@
+diff --git a/tools/llvm-config/llvm-config.cpp b/tools/llvm-config/llvm-config.cpp
+index 94d426b..37f7794 100644
+--- a/tools/llvm-config/llvm-config.cpp
++++ b/tools/llvm-config/llvm-config.cpp
+@@ -333,6 +333,21 @@ int main(int argc, char **argv) {
+     ActiveIncludeOption = "-I" + ActiveIncludeDir;
+   }
+ 
++  /// Nix-specific multiple-output handling: override ActiveLibDir if --link-shared
++  if (!IsInDevelopmentTree) {
++    bool WantShared = true;
++    for (int i = 1; i < argc; ++i) {
++      StringRef Arg = argv[i];
++      if (Arg == "--link-shared")
++        WantShared = true;
++      else if (Arg == "--link-static")
++        WantShared = false; // the last one wins
++    }
++
++    if (WantShared)
++      ActiveLibDir = std::string("@lib@") + "/lib" + LLVM_LIBDIR_SUFFIX;
++  }
++
+   /// We only use `shared library` mode in cases where the static library form
+   /// of the components provided are not available; note however that this is
+   /// skipped if we're run from within the build dir. However, once installed,
diff --git a/nixpkgs/pkgs/development/compilers/llvm/5/llvm.nix b/nixpkgs/pkgs/development/compilers/llvm/5/llvm.nix
new file mode 100644
index 000000000000..41dc20ec4fe3
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/5/llvm.nix
@@ -0,0 +1,160 @@
+{ stdenv
+, fetch
+, cmake
+, python
+, libffi
+, libbfd
+, libxml2
+, ncurses
+, version
+, release_version
+, zlib
+, libcxxabi
+, debugVersion ? false
+, enableManpages ? false
+, enableSharedLibraries ? !enableManpages
+}:
+
+let
+  src = fetch "llvm" "0g1bbj2n6xv4p1n6hh17vj3vpvg56wacipc81dgwga9mg2lys8nm";
+
+  # Used when creating a version-suffixed symlink of libLLVM.dylib
+  shortVersion = with stdenv.lib;
+    concatStringsSep "." (take 2 (splitString "." release_version));
+in stdenv.mkDerivation (rec {
+  name = "llvm-${version}";
+
+  unpackPhase = ''
+    unpackFile ${src}
+    mv llvm-${version}* llvm
+    sourceRoot=$PWD/llvm
+  '';
+
+  outputs = [ "out" "python" ]
+    ++ stdenv.lib.optional enableSharedLibraries "lib";
+
+  nativeBuildInputs = [ cmake python ]
+    ++ stdenv.lib.optional enableManpages python.pkgs.sphinx;
+
+  buildInputs = [ libxml2 libffi ];
+
+  propagatedBuildInputs = [ ncurses zlib ];
+
+  postPatch = stdenv.lib.optionalString stdenv.isDarwin ''
+    substituteInPlace cmake/modules/AddLLVM.cmake \
+      --replace 'set(_install_name_dir INSTALL_NAME_DIR "@rpath")' "set(_install_name_dir)" \
+      --replace 'set(_install_rpath "@loader_path/../lib" ''${extra_libdir})' ""
+  ''
+  # Patch llvm-config to return correct library path based on --link-{shared,static}.
+  + stdenv.lib.optionalString (enableSharedLibraries) ''
+    substitute '${./llvm-outputs.patch}' ./llvm-outputs.patch --subst-var lib
+    patch -p1 < ./llvm-outputs.patch
+  '' + ''
+    # FileSystem permissions tests fail with various special bits
+    substituteInPlace unittests/Support/CMakeLists.txt \
+      --replace "Path.cpp" ""
+    rm unittests/Support/Path.cpp
+  '' + stdenv.lib.optionalString stdenv.isAarch64 ''
+    patch -p0 < ${../aarch64.patch}
+  '' + stdenv.lib.optionalString stdenv.hostPlatform.isMusl ''
+    patch -p1 -i ${../TLI-musl.patch}
+    substituteInPlace unittests/Support/CMakeLists.txt \
+      --replace "add_subdirectory(DynamicLibrary)" ""
+    rm unittests/Support/DynamicLibrary/DynamicLibraryTest.cpp
+  '';
+
+  # hacky fix: created binaries need to be run before installation
+  preBuild = ''
+    mkdir -p $out/
+    ln -sv $PWD/lib $out
+  '';
+
+  cmakeFlags = with stdenv; [
+    "-DCMAKE_BUILD_TYPE=${if debugVersion then "Debug" else "Release"}"
+    "-DLLVM_INSTALL_UTILS=ON"  # Needed by rustc
+    "-DLLVM_BUILD_TESTS=ON"
+    "-DLLVM_ENABLE_FFI=ON"
+    "-DLLVM_ENABLE_RTTI=ON"
+
+    "-DLLVM_HOST_TRIPLE=${stdenv.hostPlatform.config}"
+    "-DLLVM_DEFAULT_TARGET_TRIPLE=${stdenv.hostPlatform.config}"
+    "-DTARGET_TRIPLE=${stdenv.hostPlatform.config}"
+  ]
+  ++ stdenv.lib.optional enableSharedLibraries
+    "-DLLVM_LINK_LLVM_DYLIB=ON"
+  ++ stdenv.lib.optionals enableManpages [
+    "-DLLVM_BUILD_DOCS=ON"
+    "-DLLVM_ENABLE_SPHINX=ON"
+    "-DSPHINX_OUTPUT_MAN=ON"
+    "-DSPHINX_OUTPUT_HTML=OFF"
+    "-DSPHINX_WARNINGS_AS_ERRORS=OFF"
+  ]
+  ++ stdenv.lib.optional (!isDarwin)
+    "-DLLVM_BINUTILS_INCDIR=${libbfd.dev}/include"
+  ++ stdenv.lib.optionals (isDarwin) [
+    "-DLLVM_ENABLE_LIBCXX=ON"
+    "-DCAN_TARGET_i386=false"
+  ];
+
+  postBuild = ''
+    rm -fR $out
+  '';
+
+  preCheck = ''
+    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PWD/lib
+  '';
+
+  postInstall = ''
+    mkdir -p $python/share
+    mv $out/share/opt-viewer $python/share/opt-viewer
+  ''
+  + stdenv.lib.optionalString enableSharedLibraries ''
+    moveToOutput "lib/libLLVM-*" "$lib"
+    moveToOutput "lib/libLLVM${stdenv.hostPlatform.extensions.sharedLibrary}" "$lib"
+    moveToOutput "lib/libLTO${stdenv.hostPlatform.extensions.sharedLibrary}" "$lib"
+    substituteInPlace "$out/lib/cmake/llvm/LLVMExports-${if debugVersion then "debug" else "release"}.cmake" \
+      --replace "\''${_IMPORT_PREFIX}/lib/libLLVM-" "$lib/lib/libLLVM-"
+  ''
+  + stdenv.lib.optionalString (stdenv.isDarwin && enableSharedLibraries) ''
+    substituteInPlace "$out/lib/cmake/llvm/LLVMExports-${if debugVersion then "debug" else "release"}.cmake" \
+      --replace "\''${_IMPORT_PREFIX}/lib/libLLVM.dylib" "$lib/lib/libLLVM.dylib" \
+      --replace "\''${_IMPORT_PREFIX}/lib/libLTO.dylib" "$lib/lib/libLTO.dylib"
+    ln -s $lib/lib/libLLVM.dylib $lib/lib/libLLVM-${shortVersion}.dylib
+    ln -s $lib/lib/libLLVM.dylib $lib/lib/libLLVM-${release_version}.dylib
+  '';
+
+  doCheck = stdenv.isLinux && (!stdenv.isi686);
+
+  checkTarget = "check-all";
+
+  enableParallelBuilding = true;
+
+  passthru.src = src;
+
+  requiredSystemFeatures = [ "big-parallel" ];
+  meta = {
+    description = "Collection of modular and reusable compiler and toolchain technologies";
+    homepage    = http://llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    maintainers = with stdenv.lib.maintainers; [ lovek323 raskin dtzWill ];
+    platforms   = stdenv.lib.platforms.all;
+  };
+} // stdenv.lib.optionalAttrs enableManpages {
+  name = "llvm-manpages-${version}";
+
+  buildPhase = ''
+    make docs-llvm-man
+  '';
+
+  propagatedBuildInputs = [];
+
+  installPhase = ''
+    make -C docs install
+  '';
+
+  outputs = [ "out" ];
+
+  doCheck = false;
+
+  meta.description = "man pages for LLVM ${version}";
+})
diff --git a/nixpkgs/pkgs/development/compilers/llvm/5/openmp.nix b/nixpkgs/pkgs/development/compilers/llvm/5/openmp.nix
new file mode 100644
index 000000000000..901015bf2ff4
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/5/openmp.nix
@@ -0,0 +1,25 @@
+{ stdenv
+, fetch
+, cmake
+, llvm
+, perl
+, version
+}:
+
+stdenv.mkDerivation {
+  name = "openmp-${version}";
+
+  src = fetch "openmp" "0p2n52676wlq6y9q99n5pivq6pvvda1p994r69fxj206ahn59jir";
+
+  nativeBuildInputs = [ cmake perl ];
+  buildInputs = [ llvm ];
+
+  enableParallelBuilding = true;
+
+  meta = {
+    description = "Components required to build an executable OpenMP program";
+    homepage    = http://openmp.llvm.org/;
+    license     = stdenv.lib.licenses.mit;
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/5/sanitizers-nongnu.patch b/nixpkgs/pkgs/development/compilers/llvm/5/sanitizers-nongnu.patch
new file mode 100644
index 000000000000..c9ddfe45c898
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/5/sanitizers-nongnu.patch
@@ -0,0 +1,370 @@
+From 3e1fcb7d4909db8f0f7dd0109b2eee20115c8be3 Mon Sep 17 00:00:00 2001
+From: "Jory A. Pratt" <anarchy@gentoo.org>
+Date: Sat, 9 Sep 2017 08:31:15 -0500
+Subject: [PATCH] Ported to compiler-rt-sanitizers-5.0.0. Taken from
+
+https://gist.githubusercontent.com/pwaller/2337f3290f12634cad3e3730cff0a6c1/raw/83c87a8585e2f9662494db5662e5361beb093c26/nongnu.patch
+Signed-off-by: Jory A. Pratt <anarchy@gentoo.org>
+
+Taken from gentoo-musl project, with a few additional minor fixes.
+---
+ lib/asan/asan_linux.cc                             |  4 +--
+ lib/interception/interception_linux.cc             |  2 +-
+ lib/interception/interception_linux.h              |  2 +-
+ lib/msan/msan_linux.cc                             |  2 +-
+ .../sanitizer_common_interceptors_ioctl.inc        |  4 +--
+ lib/sanitizer_common/sanitizer_common_syscalls.inc |  2 +-
+ lib/sanitizer_common/sanitizer_linux_libcdep.cc    | 12 +++----
+ lib/sanitizer_common/sanitizer_platform.h          |  7 ++++
+ .../sanitizer_platform_interceptors.h              |  2 +-
+ .../sanitizer_platform_limits_posix.cc             | 40 +++++++++++++---------
+ lib/tsan/rtl/tsan_platform_linux.cc                |  2 +-
+ 11 files changed, 47 insertions(+), 32 deletions(-)
+
+diff --git a/lib/asan/asan_linux.cc b/lib/asan/asan_linux.cc
+index 6d47ba432..c58dd4864 100644
+--- a/lib/asan/asan_linux.cc
++++ b/lib/asan/asan_linux.cc
+@@ -39,7 +39,7 @@
+ #include <sys/link_elf.h>
+ #endif
+ 
+-#if SANITIZER_ANDROID || SANITIZER_FREEBSD
++#if SANITIZER_ANDROID || SANITIZER_FREEBSD || SANITIZER_NONGNU
+ #include <ucontext.h>
+ extern "C" void* _DYNAMIC;
+ #else
+@@ -86,7 +86,7 @@ void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
+   UNIMPLEMENTED();
+ }
+ 
+-#if SANITIZER_ANDROID
++#if SANITIZER_ANDROID || SANITIZER_NONGNU
+ // FIXME: should we do anything for Android?
+ void AsanCheckDynamicRTPrereqs() {}
+ void AsanCheckIncompatibleRT() {}
+diff --git a/lib/interception/interception_linux.cc b/lib/interception/interception_linux.cc
+index 6e908ac01..76c1688ce 100644
+--- a/lib/interception/interception_linux.cc
++++ b/lib/interception/interception_linux.cc
+@@ -24,7 +24,7 @@ bool GetRealFunctionAddress(const char *func_name, uptr *func_addr,
+   return real == wrapper;
+ }
+ 
+-#if !defined(__ANDROID__)  // android does not have dlvsym
++#if !defined(__ANDROID__) && defined(__GLIBC__)  // android does not have dlvsym
+ void *GetFuncAddrVer(const char *func_name, const char *ver) {
+   return dlvsym(RTLD_NEXT, func_name, ver);
+ }
+diff --git a/lib/interception/interception_linux.h b/lib/interception/interception_linux.h
+index 27a66c882..f60c38991 100644
+--- a/lib/interception/interception_linux.h
++++ b/lib/interception/interception_linux.h
+@@ -34,7 +34,7 @@ void *GetFuncAddrVer(const char *func_name, const char *ver);
+       (::__interception::uptr) & (func),                                   \
+       (::__interception::uptr) & WRAP(func))
+ 
+-#if !defined(__ANDROID__)  // android does not have dlvsym
++#if !defined(__ANDROID__) && !SANITIZER_NONGNU // android does not have dlvsym
+ #define INTERCEPT_FUNCTION_VER_LINUX_OR_FREEBSD(func, symver) \
+   (::__interception::real_##func = (func##_f)(                \
+        unsigned long)::__interception::GetFuncAddrVer(#func, symver))
+diff --git a/lib/msan/msan_linux.cc b/lib/msan/msan_linux.cc
+index 0a687f620..0852d97d7 100644
+--- a/lib/msan/msan_linux.cc
++++ b/lib/msan/msan_linux.cc
+@@ -13,7 +13,7 @@
+ //===----------------------------------------------------------------------===//
+ 
+ #include "sanitizer_common/sanitizer_platform.h"
+-#if SANITIZER_FREEBSD || SANITIZER_LINUX
++#if SANITIZER_FREEBSD || SANITIZER_LINUX && !SANITIZER_NONGNU
+ 
+ #include "msan.h"
+ #include "msan_thread.h"
+diff --git a/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc b/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
+index 4ed9afedf..64f584e93 100644
+--- a/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
++++ b/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
+@@ -100,7 +100,7 @@ static void ioctl_table_fill() {
+   _(SIOCGETVIFCNT, WRITE, struct_sioc_vif_req_sz);
+ #endif
+ 
+-#if SANITIZER_LINUX
++#if SANITIZER_LINUX && !SANITIZER_NONGNU
+   // Conflicting request ids.
+   // _(CDROMAUDIOBUFSIZ, NONE, 0);
+   // _(SNDCTL_TMR_CONTINUE, NONE, 0);
+@@ -361,7 +361,7 @@ static void ioctl_table_fill() {
+   _(VT_WAITACTIVE, NONE, 0);
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   // _(SIOCDEVPLIP, WRITE, struct_ifreq_sz); // the same as EQL_ENSLAVE
+   _(CYGETDEFTHRESH, WRITE, sizeof(int));
+   _(CYGETDEFTIMEOUT, WRITE, sizeof(int));
+diff --git a/lib/sanitizer_common/sanitizer_common_syscalls.inc b/lib/sanitizer_common/sanitizer_common_syscalls.inc
+index 469c8eb7e..24f87867d 100644
+--- a/lib/sanitizer_common/sanitizer_common_syscalls.inc
++++ b/lib/sanitizer_common/sanitizer_common_syscalls.inc
+@@ -2038,7 +2038,7 @@ POST_SYSCALL(setrlimit)(long res, long resource, void *rlim) {
+   }
+ }
+ 
+-#if !SANITIZER_ANDROID
++#if !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ PRE_SYSCALL(prlimit64)(long pid, long resource, const void *new_rlim,
+                        void *old_rlim) {
+   if (new_rlim) PRE_READ(new_rlim, struct_rlimit64_sz);
+diff --git a/lib/sanitizer_common/sanitizer_linux_libcdep.cc b/lib/sanitizer_common/sanitizer_linux_libcdep.cc
+index 52196db12..045d9331f 100644
+--- a/lib/sanitizer_common/sanitizer_linux_libcdep.cc
++++ b/lib/sanitizer_common/sanitizer_linux_libcdep.cc
+@@ -148,7 +148,7 @@ bool SanitizerGetThreadName(char *name, int max_len) {
+ #endif
+ }
+ 
+-#if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO
++#if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO && !SANITIZER_NONGNU
+ static uptr g_tls_size;
+ 
+ #ifdef __i386__
+@@ -176,11 +176,11 @@ void InitTlsSize() {
+ }
+ #else
+ void InitTlsSize() { }
+-#endif  // !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO
++#endif  // !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO && !SANITIZER_NONGNU
+ 
+ #if (defined(__x86_64__) || defined(__i386__) || defined(__mips__) \
+     || defined(__aarch64__) || defined(__powerpc64__) || defined(__s390__) \
+-    || defined(__arm__)) && SANITIZER_LINUX && !SANITIZER_ANDROID
++    || defined(__arm__)) && SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ // sizeof(struct pthread) from glibc.
+ static atomic_uintptr_t kThreadDescriptorSize;
+ 
+@@ -335,7 +335,7 @@ uptr ThreadSelf() {
+ 
+ #if !SANITIZER_GO
+ static void GetTls(uptr *addr, uptr *size) {
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ # if defined(__x86_64__) || defined(__i386__) || defined(__s390__)
+   *addr = ThreadSelf();
+   *size = GetTlsSize();
+@@ -362,7 +362,7 @@ static void GetTls(uptr *addr, uptr *size) {
+     *addr = (uptr) dtv[2];
+     *size = (*addr == 0) ? 0 : ((uptr) segbase[0] - (uptr) dtv[2]);
+   }
+-#elif SANITIZER_ANDROID
++#elif SANITIZER_ANDROID || SANITIZER_NONGNU
+   *addr = 0;
+   *size = 0;
+ #else
+@@ -373,7 +373,7 @@ static void GetTls(uptr *addr, uptr *size) {
+ 
+ #if !SANITIZER_GO
+ uptr GetTlsSize() {
+-#if SANITIZER_FREEBSD || SANITIZER_ANDROID
++#if SANITIZER_FREEBSD || SANITIZER_ANDROID || SANITIZER_NONGNU
+   uptr addr, size;
+   GetTls(&addr, &size);
+   return size;
+diff --git a/lib/sanitizer_common/sanitizer_platform.h b/lib/sanitizer_common/sanitizer_platform.h
+index 396f7c934..5af6f1ed5 100644
+--- a/lib/sanitizer_common/sanitizer_platform.h
++++ b/lib/sanitizer_common/sanitizer_platform.h
+@@ -175,6 +175,13 @@
+ # define SANITIZER_ARM 0
+ #endif
+ 
++
++#if defined(__linux__) && !defined(__GLIBC__)
++# define SANITIZER_NONGNU 1
++#else
++# define SANITIZER_NONGNU 0
++#endif
++
+ // By default we allow to use SizeClassAllocator64 on 64-bit platform.
+ // But in some cases (e.g. AArch64's 39-bit address space) SizeClassAllocator64
+ // does not work well and we need to fallback to SizeClassAllocator32.
+diff --git a/lib/sanitizer_common/sanitizer_platform_interceptors.h b/lib/sanitizer_common/sanitizer_platform_interceptors.h
+index 0380cee92..0a39abbd0 100644
+--- a/lib/sanitizer_common/sanitizer_platform_interceptors.h
++++ b/lib/sanitizer_common/sanitizer_platform_interceptors.h
+@@ -31,7 +31,7 @@
+ # define SI_POSIX 0
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ # define SI_LINUX_NOT_ANDROID 1
+ #else
+ # define SI_LINUX_NOT_ANDROID 0
+diff --git a/lib/sanitizer_common/sanitizer_platform_limits_posix.cc b/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
+index 83f4fd22f..fa8c1b8bd 100644
+--- a/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
++++ b/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
+@@ -14,6 +14,9 @@
+ 
+ #include "sanitizer_platform.h"
+ 
++// Workaround musl <--> linux conflicting definition of 'struct sysinfo'
++#define _LINUX_SYSINFO_H
++
+ #if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_MAC
+ // Tests in this file assume that off_t-dependent data structures match the
+ // libc ABI. For example, struct dirent here is what readdir() function (as
+@@ -138,12 +141,14 @@ typedef struct user_fpregs elf_fpregset_t;
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+ #include <glob.h>
+-#include <obstack.h>
++#  if !SANITIZER_NONGNU
++#    include <obstack.h>
++#  endif
+ #include <mqueue.h>
+-#include <net/if_ppp.h>
+-#include <netax25/ax25.h>
+-#include <netipx/ipx.h>
+-#include <netrom/netrom.h>
++#include <linux/if_ppp.h>
++#include <linux/ax25.h>
++#include <linux/ipx.h>
++#include <linux/netrom.h>
+ #if HAVE_RPC_XDR_H
+ # include <rpc/xdr.h>
+ #elif HAVE_TIRPC_RPC_XDR_H
+@@ -159,7 +164,8 @@ typedef struct user_fpregs elf_fpregset_t;
+ # include <sys/procfs.h>
+ #endif
+ #include <sys/user.h>
+-#include <sys/ustat.h>
++// #include <sys/ustat.h>
++#include <sys/statfs.h>
+ #include <linux/cyclades.h>
+ #include <linux/if_eql.h>
+ #include <linux/if_plip.h>
+@@ -251,7 +257,7 @@ namespace __sanitizer {
+   unsigned struct_itimerspec_sz = sizeof(struct itimerspec);
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   unsigned struct_ustat_sz = sizeof(struct ustat);
+   unsigned struct_rlimit64_sz = sizeof(struct rlimit64);
+   unsigned struct_statvfs64_sz = sizeof(struct statvfs64);
+@@ -309,7 +315,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(ElfW(Phdr));
+ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+ #endif
+ 
+-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
++#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   int glob_nomatch = GLOB_NOMATCH;
+   int glob_altdirfunc = GLOB_ALTDIRFUNC;
+ #endif
+@@ -403,7 +409,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned struct_termios_sz = sizeof(struct termios);
+   unsigned struct_winsize_sz = sizeof(struct winsize);
+ 
+-#if SANITIZER_LINUX
++#if SANITIZER_LINUX && !SANITIZER_NONGNU
+   unsigned struct_arpreq_sz = sizeof(struct arpreq);
+   unsigned struct_cdrom_msf_sz = sizeof(struct cdrom_msf);
+   unsigned struct_cdrom_multisession_sz = sizeof(struct cdrom_multisession);
+@@ -453,7 +459,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned struct_vt_mode_sz = sizeof(struct vt_mode);
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   unsigned struct_ax25_parms_struct_sz = sizeof(struct ax25_parms_struct);
+   unsigned struct_cyclades_monitor_sz = sizeof(struct cyclades_monitor);
+ #if EV_VERSION > (0x010000)
+@@ -821,7 +827,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned IOCTL_VT_WAITACTIVE = VT_WAITACTIVE;
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   unsigned IOCTL_CYGETDEFTHRESH = CYGETDEFTHRESH;
+   unsigned IOCTL_CYGETDEFTIMEOUT = CYGETDEFTIMEOUT;
+   unsigned IOCTL_CYGETMON = CYGETMON;
+@@ -976,7 +982,7 @@ CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phdr);
+ CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phnum);
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
++#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ CHECK_TYPE_SIZE(glob_t);
+ CHECK_SIZE_AND_OFFSET(glob_t, gl_pathc);
+ CHECK_SIZE_AND_OFFSET(glob_t, gl_pathv);
+@@ -1010,6 +1016,7 @@ CHECK_TYPE_SIZE(iovec);
+ CHECK_SIZE_AND_OFFSET(iovec, iov_base);
+ CHECK_SIZE_AND_OFFSET(iovec, iov_len);
+ 
++#if !SANITIZER_NONGNU
+ CHECK_TYPE_SIZE(msghdr);
+ CHECK_SIZE_AND_OFFSET(msghdr, msg_name);
+ CHECK_SIZE_AND_OFFSET(msghdr, msg_namelen);
+@@ -1023,6 +1030,7 @@ CHECK_TYPE_SIZE(cmsghdr);
+ CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_len);
+ CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_level);
+ CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_type);
++#endif
+ 
+ COMPILER_CHECK(sizeof(__sanitizer_dirent) <= sizeof(dirent));
+ CHECK_SIZE_AND_OFFSET(dirent, d_ino);
+@@ -1125,7 +1133,7 @@ CHECK_SIZE_AND_OFFSET(mntent, mnt_passno);
+ 
+ CHECK_TYPE_SIZE(ether_addr);
+ 
+-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
++#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ CHECK_TYPE_SIZE(ipc_perm);
+ # if SANITIZER_FREEBSD
+ CHECK_SIZE_AND_OFFSET(ipc_perm, key);
+@@ -1186,7 +1194,7 @@ CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_dstaddr);
+ CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_data);
+ #endif
+ 
+-#if SANITIZER_LINUX
++#if SANITIZER_LINUX && !SANITIZER_NONGNU
+ COMPILER_CHECK(sizeof(__sanitizer_mallinfo) == sizeof(struct mallinfo));
+ #endif
+ 
+@@ -1236,7 +1244,7 @@ COMPILER_CHECK(__sanitizer_XDR_DECODE == XDR_DECODE);
+ COMPILER_CHECK(__sanitizer_XDR_FREE == XDR_FREE);
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ COMPILER_CHECK(sizeof(__sanitizer_FILE) <= sizeof(FILE));
+ CHECK_SIZE_AND_OFFSET(FILE, _flags);
+ CHECK_SIZE_AND_OFFSET(FILE, _IO_read_ptr);
+@@ -1255,7 +1263,7 @@ CHECK_SIZE_AND_OFFSET(FILE, _chain);
+ CHECK_SIZE_AND_OFFSET(FILE, _fileno);
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ COMPILER_CHECK(sizeof(__sanitizer__obstack_chunk) <= sizeof(_obstack_chunk));
+ CHECK_SIZE_AND_OFFSET(_obstack_chunk, limit);
+ CHECK_SIZE_AND_OFFSET(_obstack_chunk, prev);
+diff --git a/lib/tsan/rtl/tsan_platform_linux.cc b/lib/tsan/rtl/tsan_platform_linux.cc
+index ead1e5704..2c020e3fe 100644
+--- a/lib/tsan/rtl/tsan_platform_linux.cc
++++ b/lib/tsan/rtl/tsan_platform_linux.cc
+@@ -284,7 +284,7 @@ void InitializePlatform() {
+ // This is required to properly "close" the fds, because we do not see internal
+ // closes within glibc. The code is a pure hack.
+ int ExtractResolvFDs(void *state, int *fds, int nfd) {
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   int cnt = 0;
+   struct __res_state *statp = (struct __res_state*)state;
+   for (int i = 0; i < MAXNS && cnt < nfd; i++) {
+-- 
+2.16.2
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/6/clang/default.nix b/nixpkgs/pkgs/development/compilers/llvm/6/clang/default.nix
new file mode 100644
index 000000000000..840567496785
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/6/clang/default.nix
@@ -0,0 +1,106 @@
+{ stdenv, fetch, cmake, libxml2, llvm, version, clang-tools-extra_src, python
+, fixDarwinDylibNames
+, enableManpages ? false
+}:
+
+let
+  gcc = if stdenv.cc.isGNU then stdenv.cc.cc else stdenv.cc.cc.gcc;
+  self = stdenv.mkDerivation ({
+    name = "clang-${version}";
+
+    unpackPhase = ''
+      unpackFile ${fetch "cfe" "0rxn4rh7rrnsqbdgp4gzc8ishbkryhpl1kd3mpnxzpxxhla3y93w"}
+      mv cfe-${version}* clang
+      sourceRoot=$PWD/clang
+      unpackFile ${clang-tools-extra_src}
+      mv clang-tools-extra-* $sourceRoot/tools/extra
+    '';
+
+    nativeBuildInputs = [ cmake python ]
+      ++ stdenv.lib.optional enableManpages python.pkgs.sphinx;
+
+    buildInputs = [ libxml2 llvm ]
+      ++ stdenv.lib.optional stdenv.isDarwin fixDarwinDylibNames;
+
+    cmakeFlags = [
+      "-DCMAKE_CXX_FLAGS=-std=c++11"
+    ] ++ stdenv.lib.optionals enableManpages [
+      "-DCLANG_INCLUDE_DOCS=ON"
+      "-DLLVM_ENABLE_SPHINX=ON"
+      "-DSPHINX_OUTPUT_MAN=ON"
+      "-DSPHINX_OUTPUT_HTML=OFF"
+      "-DSPHINX_WARNINGS_AS_ERRORS=OFF"
+    ];
+
+    patches = [ ./purity.patch ];
+
+    postPatch = ''
+      sed -i -e 's/DriverArgs.hasArg(options::OPT_nostdlibinc)/true/' \
+             -e 's/Args.hasArg(options::OPT_nostdlibinc)/true/' \
+             lib/Driver/ToolChains/*.cpp
+
+      # Patch for standalone doc building
+      sed -i '1s,^,find_package(Sphinx REQUIRED)\n,' docs/CMakeLists.txt
+    '' + stdenv.lib.optionalString stdenv.hostPlatform.isMusl ''
+      sed -i -e 's/lgcc_s/lgcc_eh/' lib/Driver/ToolChains/*.cpp
+    '';
+
+    outputs = [ "out" "lib" "python" ];
+
+    # Clang expects to find LLVMgold in its own prefix
+    postInstall = ''
+      if [ -e ${llvm}/lib/LLVMgold.so ]; then
+        ln -sv ${llvm}/lib/LLVMgold.so $out/lib
+      fi
+
+      ln -sv $out/bin/clang $out/bin/cpp
+
+      # Move libclang to 'lib' output
+      moveToOutput "lib/libclang.*" "$lib"
+      substituteInPlace $out/lib/cmake/clang/ClangTargets-release.cmake \
+          --replace "\''${_IMPORT_PREFIX}/lib/libclang." "$lib/lib/libclang."
+
+      mkdir -p $python/bin $python/share/clang/
+      mv $out/bin/{git-clang-format,scan-view} $python/bin
+      if [ -e $out/bin/set-xcode-analyzer ]; then
+        mv $out/bin/set-xcode-analyzer $python/bin
+      fi
+      mv $out/share/clang/*.py $python/share/clang
+      rm $out/bin/c-index-test
+    '';
+
+    enableParallelBuilding = true;
+
+    passthru = {
+      isClang = true;
+      inherit llvm;
+    } // stdenv.lib.optionalAttrs stdenv.targetPlatform.isLinux {
+      inherit gcc;
+    };
+
+    meta = {
+      description = "A c, c++, objective-c, and objective-c++ frontend for the llvm compiler";
+      homepage    = http://llvm.org/;
+      license     = stdenv.lib.licenses.ncsa;
+      platforms   = stdenv.lib.platforms.all;
+    };
+  } // stdenv.lib.optionalAttrs enableManpages {
+    name = "clang-manpages-${version}";
+
+    buildPhase = ''
+      make docs-clang-man
+    '';
+
+    installPhase = ''
+      mkdir -p $out/share/man/man1
+      # Manually install clang manpage
+      cp docs/man/*.1 $out/share/man/man1/
+    '';
+
+    outputs = [ "out" ];
+
+    doCheck = false;
+
+    meta.description = "man page for Clang ${version}";
+  });
+in self
diff --git a/nixpkgs/pkgs/development/compilers/llvm/6/clang/purity.patch b/nixpkgs/pkgs/development/compilers/llvm/6/clang/purity.patch
new file mode 100644
index 000000000000..b30d0d0b5d5b
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/6/clang/purity.patch
@@ -0,0 +1,30 @@
+From 4add81bba40dcec62c4ea4481be8e35ac53e89d8 Mon Sep 17 00:00:00 2001
+From: Will Dietz <w@wdtz.org>
+Date: Thu, 18 May 2017 11:56:12 -0500
+Subject: [PATCH] "purity" patch for 5.0
+
+---
+ lib/Driver/ToolChains/Gnu.cpp | 7 -------
+ 1 file changed, 7 deletions(-)
+
+diff --git a/lib/Driver/ToolChains/Gnu.cpp b/lib/Driver/ToolChains/Gnu.cpp
+index fe3c0191bb..c6a482bece 100644
+--- a/lib/Driver/ToolChains/Gnu.cpp
++++ b/lib/Driver/ToolChains/Gnu.cpp
+@@ -494,13 +494,6 @@ void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
+   if (!Args.hasArg(options::OPT_static)) {
+     if (Args.hasArg(options::OPT_rdynamic))
+       CmdArgs.push_back("-export-dynamic");
+-
+-    if (!Args.hasArg(options::OPT_shared)) {
+-      const std::string Loader =
+-          D.DyldPrefix + ToolChain.getDynamicLinker(Args);
+-      CmdArgs.push_back("-dynamic-linker");
+-      CmdArgs.push_back(Args.MakeArgString(Loader));
+-    }
+   }
+ 
+   CmdArgs.push_back("-o");
+-- 
+2.11.0
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/6/compiler-rt-codesign.patch b/nixpkgs/pkgs/development/compilers/llvm/6/compiler-rt-codesign.patch
new file mode 100644
index 000000000000..8f4c76bca1eb
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/6/compiler-rt-codesign.patch
@@ -0,0 +1,155 @@
+From 3dec5f3475a26aeb4678627795c4b67c6b7b4785 Mon Sep 17 00:00:00 2001
+From: Will Dietz <w@wdtz.org>
+Date: Tue, 19 Sep 2017 13:13:06 -0500
+Subject: [PATCH] remove codesign use on Apple, disable ios sim testing that
+ needs it
+
+---
+ cmake/Modules/AddCompilerRT.cmake |  8 ------
+ test/asan/CMakeLists.txt          | 52 ---------------------------------------
+ test/tsan/CMakeLists.txt          | 47 -----------------------------------
+ 3 files changed, 107 deletions(-)
+
+diff --git a/cmake/Modules/AddCompilerRT.cmake b/cmake/Modules/AddCompilerRT.cmake
+index bc5fb9ff7..b64eb4246 100644
+--- a/cmake/Modules/AddCompilerRT.cmake
++++ b/cmake/Modules/AddCompilerRT.cmake
+@@ -210,14 +210,6 @@ function(add_compiler_rt_runtime name type)
+         set_target_properties(${libname} PROPERTIES IMPORT_PREFIX "")
+         set_target_properties(${libname} PROPERTIES IMPORT_SUFFIX ".lib")
+       endif()
+-      if(APPLE)
+-        # Ad-hoc sign the dylibs
+-        add_custom_command(TARGET ${libname}
+-          POST_BUILD  
+-          COMMAND codesign --sign - $<TARGET_FILE:${libname}>
+-          WORKING_DIRECTORY ${COMPILER_RT_LIBRARY_OUTPUT_DIR}
+-        )
+-      endif()
+     endif()
+     install(TARGETS ${libname}
+       ARCHIVE DESTINATION ${COMPILER_RT_LIBRARY_INSTALL_DIR}
+diff --git a/test/asan/CMakeLists.txt b/test/asan/CMakeLists.txt
+index 8bfc15b5c..f23d0f71a 100644
+--- a/test/asan/CMakeLists.txt
++++ b/test/asan/CMakeLists.txt
+@@ -83,58 +83,6 @@ foreach(arch ${ASAN_TEST_ARCH})
+   endif()
+ endforeach()
+ 
+-# iOS and iOS simulator test suites
+-# These are not added into "check-all", in order to run these tests, use
+-# "check-asan-iossim-x86_64" and similar. They also require that an extra env
+-# variable to select which iOS device or simulator to use, e.g.:
+-# SANITIZER_IOSSIM_TEST_DEVICE_IDENTIFIER="iPhone 6"
+-if(APPLE)
+-  set(EXCLUDE_FROM_ALL ON)
+-
+-  set(ASAN_TEST_TARGET_CC ${COMPILER_RT_TEST_COMPILER})
+-  set(ASAN_TEST_IOS "1")
+-  pythonize_bool(ASAN_TEST_IOS)
+-  set(ASAN_TEST_DYNAMIC True)
+-
+-  foreach(arch ${DARWIN_iossim_ARCHS})
+-    set(ASAN_TEST_IOSSIM "1")
+-    pythonize_bool(ASAN_TEST_IOSSIM)
+-    set(ASAN_TEST_TARGET_ARCH ${arch})
+-    set(ASAN_TEST_TARGET_CFLAGS "-arch ${arch} -isysroot ${DARWIN_iossim_SYSROOT} ${COMPILER_RT_TEST_COMPILER_CFLAGS}")
+-    set(ASAN_TEST_CONFIG_SUFFIX "-${arch}-iossim")
+-    get_bits_for_arch(${arch} ASAN_TEST_BITS)
+-    string(TOUPPER ${arch} ARCH_UPPER_CASE)
+-    set(CONFIG_NAME "IOSSim${ARCH_UPPER_CASE}Config")
+-    configure_lit_site_cfg(
+-      ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in
+-      ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/lit.site.cfg
+-      )
+-    add_lit_testsuite(check-asan-iossim-${arch} "AddressSanitizer iOS Simulator ${arch} tests"
+-      ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/
+-      DEPENDS ${ASAN_TEST_DEPS})
+-  endforeach()
+-
+-  foreach (arch ${DARWIN_ios_ARCHS})
+-    set(ASAN_TEST_IOSSIM "0")
+-    pythonize_bool(ASAN_TEST_IOSSIM)
+-    set(ASAN_TEST_TARGET_ARCH ${arch})
+-    set(ASAN_TEST_TARGET_CFLAGS "-arch ${arch} -isysroot ${DARWIN_ios_SYSROOT} ${COMPILER_RT_TEST_COMPILER_CFLAGS}")
+-    set(ASAN_TEST_CONFIG_SUFFIX "-${arch}-ios")
+-    get_bits_for_arch(${arch} ASAN_TEST_BITS)
+-    string(TOUPPER ${arch} ARCH_UPPER_CASE)
+-    set(CONFIG_NAME "IOS${ARCH_UPPER_CASE}Config")
+-    configure_lit_site_cfg(
+-      ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in
+-      ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/lit.site.cfg
+-      )
+-    add_lit_testsuite(check-asan-ios-${arch} "AddressSanitizer iOS ${arch} tests"
+-      ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/
+-      DEPENDS ${ASAN_TEST_DEPS})
+-  endforeach()
+-
+-  set(EXCLUDE_FROM_ALL OFF)
+-endif()
+-
+ # Add unit tests.
+ if(COMPILER_RT_INCLUDE_TESTS)
+   set(ASAN_TEST_DYNAMIC False)
+diff --git a/test/tsan/CMakeLists.txt b/test/tsan/CMakeLists.txt
+index a68908612..cde0accb5 100644
+--- a/test/tsan/CMakeLists.txt
++++ b/test/tsan/CMakeLists.txt
+@@ -42,53 +42,6 @@ foreach(arch ${TSAN_TEST_ARCH})
+   list(APPEND TSAN_TESTSUITES ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME})
+ endforeach()
+ 
+-# iOS and iOS simulator test suites
+-# These are not added into "check-all", in order to run these tests, use
+-# "check-tsan-iossim-x86_64" and similar. They also require an extra environment
+-# variable to select which iOS device or simulator to use, e.g.:
+-# SANITIZER_IOSSIM_TEST_DEVICE_IDENTIFIER="iPhone 6"
+-if(APPLE)
+-  set(EXCLUDE_FROM_ALL ON)
+-
+-  set(TSAN_TEST_TARGET_CC ${COMPILER_RT_TEST_COMPILER})
+-  set(TSAN_TEST_IOS "1")
+-  pythonize_bool(TSAN_TEST_IOS)
+-
+-  set(arch "x86_64")
+-  set(TSAN_TEST_IOSSIM "1")
+-  pythonize_bool(TSAN_TEST_IOSSIM)
+-  set(TSAN_TEST_TARGET_ARCH ${arch})
+-  set(TSAN_TEST_TARGET_CFLAGS "-arch ${arch} -isysroot ${DARWIN_iossim_SYSROOT} ${COMPILER_RT_TEST_COMPILER_CFLAGS}")
+-  set(TSAN_TEST_CONFIG_SUFFIX "-${arch}-iossim")
+-  string(TOUPPER ${arch} ARCH_UPPER_CASE)
+-  set(CONFIG_NAME "IOSSim${ARCH_UPPER_CASE}Config")
+-  configure_lit_site_cfg(
+-    ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in
+-    ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/lit.site.cfg
+-    )
+-  add_lit_testsuite(check-tsan-iossim-${arch} "ThreadSanitizer iOS Simulator ${arch} tests"
+-    ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/
+-    DEPENDS ${TSAN_TEST_DEPS})
+-
+-  set(arch "arm64")
+-  set(TSAN_TEST_IOSSIM "0")
+-  pythonize_bool(TSAN_TEST_IOSSIM)
+-  set(TSAN_TEST_TARGET_ARCH ${arch})
+-  set(TSAN_TEST_TARGET_CFLAGS "-arch ${arch} -isysroot ${DARWIN_ios_SYSROOT} ${COMPILER_RT_TEST_COMPILER_CFLAGS}")
+-  set(TSAN_TEST_CONFIG_SUFFIX "-${arch}-ios")
+-  string(TOUPPER ${arch} ARCH_UPPER_CASE)
+-  set(CONFIG_NAME "IOS${ARCH_UPPER_CASE}Config")
+-  configure_lit_site_cfg(
+-    ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in
+-    ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/lit.site.cfg
+-    )
+-  add_lit_testsuite(check-tsan-ios-${arch} "ThreadSanitizer iOS Simulator ${arch} tests"
+-    ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/
+-    DEPENDS ${TSAN_TEST_DEPS})
+-
+-  set(EXCLUDE_FROM_ALL OFF)
+-endif()
+-
+ if(COMPILER_RT_INCLUDE_TESTS)
+   configure_lit_site_cfg(
+     ${CMAKE_CURRENT_SOURCE_DIR}/Unit/lit.site.cfg.in
+-- 
+2.14.1
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/6/compiler-rt.nix b/nixpkgs/pkgs/development/compilers/llvm/6/compiler-rt.nix
new file mode 100644
index 000000000000..be18a315f12a
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/6/compiler-rt.nix
@@ -0,0 +1,37 @@
+{ stdenv, version, fetch, cmake, python, llvm, libcxxabi }:
+with stdenv.lib;
+stdenv.mkDerivation rec {
+  name = "compiler-rt-${version}";
+  inherit version;
+  src = fetch "compiler-rt" "1fcr3jn24yr8lh36nc0c4ikli4744i2q9m1ik67p1jymwwaixkgl";
+
+  nativeBuildInputs = [ cmake python llvm ];
+  buildInputs = stdenv.lib.optional stdenv.hostPlatform.isDarwin libcxxabi;
+
+  configureFlags = [
+    "-DCOMPILER_RT_DEFAULT_TARGET_ONLY=ON"
+  ];
+
+  outputs = [ "out" "dev" ];
+
+  patches = [
+    ./compiler-rt-codesign.patch # Revert compiler-rt commit that makes codesign mandatory
+  ] ++ optional stdenv.hostPlatform.isMusl ./sanitizers-nongnu.patch;
+
+  # TSAN requires XPC on Darwin, which we have no public/free source files for. We can depend on the Apple frameworks
+  # to get it, but they're unfree. Since LLVM is rather central to the stdenv, we patch out TSAN support so that Hydra
+  # can build this. If we didn't do it, basically the entire nixpkgs on Darwin would have an unfree dependency and we'd
+  # get no binary cache for the entire platform. If you really find yourself wanting the TSAN, make this controllable by
+  # a flag and turn the flag off during the stdenv build.
+  postPatch = stdenv.lib.optionalString stdenv.isDarwin ''
+    substituteInPlace cmake/config-ix.cmake \
+      --replace 'set(COMPILER_RT_HAS_TSAN TRUE)' 'set(COMPILER_RT_HAS_TSAN FALSE)'
+  '';
+
+  # Hack around weird upsream RPATH bug
+  postInstall = stdenv.lib.optionalString stdenv.isDarwin ''
+    ln -s "$out/lib"/*/* "$out/lib"
+  '';
+
+  enableParallelBuilding = true;
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/6/default.nix b/nixpkgs/pkgs/development/compilers/llvm/6/default.nix
new file mode 100644
index 000000000000..ae51c19ec728
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/6/default.nix
@@ -0,0 +1,93 @@
+{ lowPrio, newScope, pkgs, stdenv, cmake, libstdcxxHook
+, libxml2, python, isl, fetchurl, overrideCC, wrapCCWith
+, buildLlvmTools # tools, but from the previous stage, for cross
+, targetLlvmLibraries # libraries, but from the next stage, for cross
+}:
+
+let
+  release_version = "6.0.1";
+  version = release_version; # differentiating these is important for rc's
+
+  fetch = name: sha256: fetchurl {
+    url = "https://releases.llvm.org/${release_version}/${name}-${version}.src.tar.xz";
+    inherit sha256;
+  };
+
+  clang-tools-extra_src = fetch "clang-tools-extra" "1w8ml7fyn4vyxmy59n2qm4r1k1kgwgwkaldp6m45fdv4g0kkfbhd";
+
+  tools = stdenv.lib.makeExtensible (tools: let
+    callPackage = newScope (tools // { inherit stdenv cmake libxml2 python isl release_version version fetch; });
+    mkExtraBuildCommands = cc: ''
+      rsrc="$out/resource-root"
+      mkdir "$rsrc"
+      ln -s "${cc}/lib/clang/${release_version}/include" "$rsrc"
+      ln -s "${targetLlvmLibraries.compiler-rt.out}/lib" "$rsrc/lib"
+      echo "-resource-dir=$rsrc" >> $out/nix-support/cc-cflags
+    '' + stdenv.lib.optionalString stdenv.targetPlatform.isLinux ''
+      echo "--gcc-toolchain=${tools.clang-unwrapped.gcc}" >> $out/nix-support/cc-cflags
+    '';
+  in {
+
+    llvm = callPackage ./llvm.nix { };
+
+    clang-unwrapped = callPackage ./clang {
+      inherit clang-tools-extra_src;
+    };
+
+    llvm-manpages = lowPrio (tools.llvm.override {
+      enableManpages = true;
+      python = pkgs.python;  # don't use python-boot
+    });
+
+    clang-manpages = lowPrio (tools.clang-unwrapped.override {
+      enableManpages = true;
+      python = pkgs.python;  # don't use python-boot
+    });
+
+    libclang = tools.clang-unwrapped.lib;
+
+    clang = if stdenv.cc.isGNU then tools.libstdcxxClang else tools.libcxxClang;
+
+    libstdcxxClang = wrapCCWith rec {
+      cc = tools.clang-unwrapped;
+      extraPackages = [
+        libstdcxxHook
+        targetLlvmLibraries.compiler-rt
+      ];
+      extraBuildCommands = mkExtraBuildCommands cc;
+    };
+
+    libcxxClang = wrapCCWith rec {
+      cc = tools.clang-unwrapped;
+      libcxx = targetLlvmLibraries.libcxx;
+      extraPackages = [
+        targetLlvmLibraries.libcxx
+        targetLlvmLibraries.libcxxabi
+        targetLlvmLibraries.compiler-rt
+      ];
+      extraBuildCommands = mkExtraBuildCommands cc;
+    };
+
+    lld = callPackage ./lld.nix {};
+
+    lldb = callPackage ./lldb.nix {};
+  });
+
+  libraries = stdenv.lib.makeExtensible (libraries: let
+    callPackage = newScope (libraries // buildLlvmTools // { inherit stdenv cmake libxml2 python isl release_version version fetch; });
+  in {
+
+    compiler-rt = callPackage ./compiler-rt.nix {};
+
+    stdenv = overrideCC stdenv buildLlvmTools.clang;
+
+    libcxxStdenv = overrideCC stdenv buildLlvmTools.libcxxClang;
+
+    libcxx = callPackage ./libc++ {};
+
+    libcxxabi = callPackage ./libc++abi.nix {};
+
+    openmp = callPackage ./openmp.nix {};
+  });
+
+in { inherit tools libraries; } // libraries // tools
diff --git a/nixpkgs/pkgs/development/compilers/llvm/6/libc++/default.nix b/nixpkgs/pkgs/development/compilers/llvm/6/libc++/default.nix
new file mode 100644
index 000000000000..3a165e9da7b1
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/6/libc++/default.nix
@@ -0,0 +1,52 @@
+{ lib, stdenv, fetch, cmake, python, libcxxabi, fixDarwinDylibNames, version }:
+
+stdenv.mkDerivation rec {
+  name = "libc++-${version}";
+
+  src = fetch "libcxx" "0rzw4qvxp6qx4l4h9amrq02gp7hbg8lw4m0sy3k60f50234gnm3n";
+
+  postUnpack = ''
+    unpackFile ${libcxxabi.src}
+    export LIBCXXABI_INCLUDE_DIR="$PWD/$(ls -d libcxxabi-${version}*)/include"
+  '';
+
+  patches = stdenv.lib.optionals stdenv.hostPlatform.isMusl [
+    ../../libcxx-0001-musl-hacks.patch
+  ];
+
+  prePatch = ''
+    substituteInPlace lib/CMakeLists.txt --replace "/usr/lib/libc++" "\''${LIBCXX_LIBCXXABI_LIB_PATH}/libc++"
+  '';
+
+  preConfigure = ''
+    # Get headers from the cxxabi source so we can see private headers not installed by the cxxabi package
+    cmakeFlagsArray=($cmakeFlagsArray -DLIBCXX_CXX_ABI_INCLUDE_PATHS="$LIBCXXABI_INCLUDE_DIR")
+  '' + lib.optionalString stdenv.hostPlatform.isMusl ''
+    patchShebangs utils/cat_files.py
+  '';
+  nativeBuildInputs = [ cmake ] ++ stdenv.lib.optional stdenv.hostPlatform.isMusl python;
+
+  buildInputs = [ libcxxabi ] ++ lib.optional stdenv.isDarwin fixDarwinDylibNames;
+
+  cmakeFlags = [
+    "-DLIBCXX_LIBCXXABI_LIB_PATH=${libcxxabi}/lib"
+    "-DLIBCXX_LIBCPPABI_VERSION=2"
+    "-DLIBCXX_CXX_ABI=libcxxabi"
+  ] ++ stdenv.lib.optional stdenv.hostPlatform.isMusl "-DLIBCXX_HAS_MUSL_LIBC=1";
+
+  enableParallelBuilding = true;
+
+  linkCxxAbi = stdenv.isLinux;
+
+  setupHooks = [
+    ../../../../../build-support/setup-hooks/role.bash
+    ./setup-hook.sh
+  ];
+
+  meta = {
+    homepage = http://libcxx.llvm.org/;
+    description = "A new implementation of the C++ standard library, targeting C++11";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/6/libc++/setup-hook.sh b/nixpkgs/pkgs/development/compilers/llvm/6/libc++/setup-hook.sh
new file mode 100644
index 000000000000..6611259165ae
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/6/libc++/setup-hook.sh
@@ -0,0 +1,6 @@
+# See pkgs/build-support/setup-hooks/role.bash
+getHostRole
+
+linkCxxAbi="@linkCxxAbi@"
+export NIX_${role_pre}CXXSTDLIB_COMPILE+=" -isystem @out@/include/c++/v1"
+export NIX_${role_pre}CXXSTDLIB_LINK=" -stdlib=libc++${linkCxxAbi:+" -lc++abi"}"
diff --git a/nixpkgs/pkgs/development/compilers/llvm/6/libc++abi.nix b/nixpkgs/pkgs/development/compilers/llvm/6/libc++abi.nix
new file mode 100644
index 000000000000..df9c784a10f4
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/6/libc++abi.nix
@@ -0,0 +1,50 @@
+{ stdenv, cmake, fetch, libcxx, libunwind, llvm, version }:
+
+stdenv.mkDerivation {
+  name = "libc++abi-${version}";
+
+  src = fetch "libcxxabi" "0prqvdj317qrc8nddaq1hh2ag9algkd9wbkj3y4mr5588k12x7r0";
+
+  nativeBuildInputs = [ cmake ];
+  buildInputs = stdenv.lib.optional (!stdenv.isDarwin && !stdenv.isFreeBSD) libunwind;
+
+  postUnpack = ''
+    unpackFile ${libcxx.src}
+    unpackFile ${llvm.src}
+    export cmakeFlags="-DLLVM_PATH=$PWD/$(ls -d llvm-*) -DLIBCXXABI_LIBCXX_PATH=$PWD/$(ls -d libcxx-*)"
+  '' + stdenv.lib.optionalString stdenv.isDarwin ''
+    export TRIPLE=x86_64-apple-darwin
+  '' + stdenv.lib.optionalString stdenv.hostPlatform.isMusl ''
+    patch -p1 -d $(ls -d libcxx-*) -i ${../libcxx-0001-musl-hacks.patch}
+  '';
+
+  installPhase = if stdenv.isDarwin
+    then ''
+      for file in lib/*.dylib; do
+        # this should be done in CMake, but having trouble figuring out
+        # the magic combination of necessary CMake variables
+        # if you fancy a try, take a look at
+        # http://www.cmake.org/Wiki/CMake_RPATH_handling
+        install_name_tool -id $out/$file $file
+      done
+      make install
+      install -d 755 $out/include
+      install -m 644 ../include/*.h $out/include
+    ''
+    else ''
+      install -d -m 755 $out/include $out/lib
+      install -m 644 lib/libc++abi.a $out/lib
+      install -m 644 lib/libc++abi.so.1.0 $out/lib
+      install -m 644 ../include/cxxabi.h $out/include
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so.1
+    '';
+
+  meta = {
+    homepage = http://libcxxabi.llvm.org/;
+    description = "A new implementation of low level support for a standard C++ library";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    maintainers = with stdenv.lib.maintainers; [ vlstill ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/6/lld.nix b/nixpkgs/pkgs/development/compilers/llvm/6/lld.nix
new file mode 100644
index 000000000000..1e68276945ec
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/6/lld.nix
@@ -0,0 +1,32 @@
+{ stdenv
+, fetch
+, cmake
+, libxml2
+, llvm
+, version
+}:
+
+stdenv.mkDerivation {
+  name = "lld-${version}";
+
+  src = fetch "lld" "04afcfq2h7ysyqxxhyhb7ig4p0vdw7mi63kh8mffl74j0rc781p7";
+
+  nativeBuildInputs = [ cmake ];
+  buildInputs = [ llvm libxml2 ];
+
+  outputs = [ "out" "dev" ];
+
+  enableParallelBuilding = true;
+
+  postInstall = ''
+    moveToOutput include "$dev"
+    moveToOutput lib "$dev"
+  '';
+
+  meta = {
+    description = "The LLVM Linker";
+    homepage    = http://lld.llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/6/lldb.nix b/nixpkgs/pkgs/development/compilers/llvm/6/lldb.nix
new file mode 100644
index 000000000000..d33de2488350
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/6/lldb.nix
@@ -0,0 +1,56 @@
+{ stdenv
+, fetch
+, cmake
+, zlib
+, ncurses
+, swig
+, which
+, libedit
+, libxml2
+, llvm
+, clang-unwrapped
+, python
+, version
+, darwin
+}:
+
+stdenv.mkDerivation {
+  name = "lldb-${version}";
+
+  src = fetch "lldb" "05178zkyh84x32n91md6wm22lkzzrrfwa5cpmgzn0yrg3y2771bb";
+
+  postPatch = ''
+    # Fix up various paths that assume llvm and clang are installed in the same place
+    sed -i 's,".*ClangConfig.cmake","${clang-unwrapped}/lib/cmake/clang/ClangConfig.cmake",' \
+      cmake/modules/LLDBStandalone.cmake
+    sed -i 's,".*tools/clang/include","${clang-unwrapped}/include",' \
+      cmake/modules/LLDBStandalone.cmake
+    sed -i 's,"$.LLVM_LIBRARY_DIR.",${llvm}/lib ${clang-unwrapped}/lib,' \
+      cmake/modules/LLDBStandalone.cmake
+  '';
+
+  nativeBuildInputs = [ cmake python which swig ];
+  buildInputs = [ ncurses zlib libedit libxml2 llvm ]
+    ++ stdenv.lib.optionals stdenv.isDarwin [ darwin.libobjc darwin.apple_sdk.libs.xpc darwin.apple_sdk.frameworks.Foundation darwin.bootstrap_cmds darwin.apple_sdk.frameworks.Carbon darwin.apple_sdk.frameworks.Cocoa darwin.cf-private ];
+
+  CXXFLAGS = "-fno-rtti";
+  hardeningDisable = [ "format" ];
+
+  cmakeFlags = [
+    "-DLLDB_CODESIGN_IDENTITY=" # codesigning makes nondeterministic
+  ];
+
+  enableParallelBuilding = true;
+
+  postInstall = ''
+    mkdir -p $out/share/man/man1
+    cp ../docs/lldb.1 $out/share/man/man1/
+  '';
+
+  meta = with stdenv.lib; {
+    description = "A next-generation high-performance debugger";
+    homepage    = http://llvm.org/;
+    license     = licenses.ncsa;
+    platforms   = platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/6/llvm-outputs.patch b/nixpkgs/pkgs/development/compilers/llvm/6/llvm-outputs.patch
new file mode 100644
index 000000000000..40096fa3497f
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/6/llvm-outputs.patch
@@ -0,0 +1,26 @@
+diff --git a/tools/llvm-config/llvm-config.cpp b/tools/llvm-config/llvm-config.cpp
+index 94d426b..37f7794 100644
+--- a/tools/llvm-config/llvm-config.cpp
++++ b/tools/llvm-config/llvm-config.cpp
+@@ -333,6 +333,21 @@ int main(int argc, char **argv) {
+     ActiveIncludeOption = "-I" + ActiveIncludeDir;
+   }
+ 
++  /// Nix-specific multiple-output handling: override ActiveLibDir if --link-shared
++  if (!IsInDevelopmentTree) {
++    bool WantShared = true;
++    for (int i = 1; i < argc; ++i) {
++      StringRef Arg = argv[i];
++      if (Arg == "--link-shared")
++        WantShared = true;
++      else if (Arg == "--link-static")
++        WantShared = false; // the last one wins
++    }
++
++    if (WantShared)
++      ActiveLibDir = std::string("@lib@") + "/lib" + LLVM_LIBDIR_SUFFIX;
++  }
++
+   /// We only use `shared library` mode in cases where the static library form
+   /// of the components provided are not available; note however that this is
+   /// skipped if we're run from within the build dir. However, once installed,
diff --git a/nixpkgs/pkgs/development/compilers/llvm/6/llvm.nix b/nixpkgs/pkgs/development/compilers/llvm/6/llvm.nix
new file mode 100644
index 000000000000..1d96513a0ece
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/6/llvm.nix
@@ -0,0 +1,173 @@
+{ stdenv
+, fetch
+, cmake
+, python
+, libffi
+, libbfd
+, libxml2
+, ncurses
+, version
+, release_version
+, zlib
+, buildPackages
+, fetchpatch
+, debugVersion ? false
+, enableManpages ? false
+, enableSharedLibraries ? true
+}:
+
+let
+  inherit (stdenv.lib) optional optionals optionalString;
+
+  src = fetch "llvm" "1qpls3vk85lydi5b4axl0809fv932qgsqgdgrk098567z4jc7mmn";
+
+  # Used when creating a version-suffixed symlink of libLLVM.dylib
+  shortVersion = with stdenv.lib;
+    concatStringsSep "." (take 2 (splitString "." release_version));
+
+in stdenv.mkDerivation (rec {
+  name = "llvm-${version}";
+
+  unpackPhase = ''
+    unpackFile ${src}
+    mv llvm-${version}* llvm
+    sourceRoot=$PWD/llvm
+  '';
+
+  outputs = [ "out" "python" ]
+    ++ optional enableSharedLibraries "lib";
+
+  nativeBuildInputs = [ cmake python ]
+    ++ optional enableManpages python.pkgs.sphinx;
+
+  buildInputs = [ libxml2 libffi ];
+
+  propagatedBuildInputs = [ ncurses zlib ];
+
+  patches = [
+    # Patches to fix tests, included in llvm_7
+    (fetchpatch {
+      url = "https://github.com/llvm-mirror/llvm/commit/737553be0c9c25c497b45a241689994f177d5a5d.patch";
+      sha256 = "0hnaxnkx7zy5yg98f1ggv8a9l0r6g19n6ygqsv26masrnlcbccli";
+    })
+    (fetchpatch {
+      url = "https://github.com/llvm-mirror/llvm/commit/1c0dd31a7837c3e2f1c4ac14e4d5ac640688bd1f.patch";
+      includes = [ "test/tools/gold/X86/common.ll" ];
+      sha256 = "0fxgrxmfnjx17w3lcq19rk68b2xksh1bynz3ina784kma7hp4wdb";
+    })
+  ];
+
+  postPatch = optionalString stdenv.isDarwin ''
+    substituteInPlace cmake/modules/AddLLVM.cmake \
+      --replace 'set(_install_name_dir INSTALL_NAME_DIR "@rpath")' "set(_install_name_dir)" \
+      --replace 'set(_install_rpath "@loader_path/../lib" ''${extra_libdir})' ""
+  ''
+  # Patch llvm-config to return correct library path based on --link-{shared,static}.
+  + optionalString (enableSharedLibraries) ''
+    substitute '${./llvm-outputs.patch}' ./llvm-outputs.patch --subst-var lib
+    patch -p1 < ./llvm-outputs.patch
+  '' + ''
+    # FileSystem permissions tests fail with various special bits
+    substituteInPlace unittests/Support/CMakeLists.txt \
+      --replace "Path.cpp" ""
+    rm unittests/Support/Path.cpp
+  '' + optionalString stdenv.hostPlatform.isMusl ''
+    patch -p1 -i ${../TLI-musl.patch}
+    substituteInPlace unittests/Support/CMakeLists.txt \
+      --replace "add_subdirectory(DynamicLibrary)" ""
+    rm unittests/Support/DynamicLibrary/DynamicLibraryTest.cpp
+  '';
+
+  # hacky fix: created binaries need to be run before installation
+  preBuild = ''
+    mkdir -p $out/
+    ln -sv $PWD/lib $out
+  '';
+
+  cmakeFlags = with stdenv; [
+    "-DCMAKE_BUILD_TYPE=${if debugVersion then "Debug" else "Release"}"
+    "-DLLVM_INSTALL_UTILS=ON"  # Needed by rustc
+    "-DLLVM_BUILD_TESTS=ON"
+    "-DLLVM_ENABLE_FFI=ON"
+    "-DLLVM_ENABLE_RTTI=ON"
+    "-DLLVM_HOST_TRIPLE=${stdenv.hostPlatform.config}"
+    "-DLLVM_DEFAULT_TARGET_TRIPLE=${stdenv.hostPlatform.config}"
+    "-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=WebAssembly"
+    "-DLLVM_ENABLE_DUMP=ON"
+  ] ++ optionals enableSharedLibraries [
+    "-DLLVM_LINK_LLVM_DYLIB=ON"
+  ] ++ optionals enableManpages [
+    "-DLLVM_BUILD_DOCS=ON"
+    "-DLLVM_ENABLE_SPHINX=ON"
+    "-DSPHINX_OUTPUT_MAN=ON"
+    "-DSPHINX_OUTPUT_HTML=OFF"
+    "-DSPHINX_WARNINGS_AS_ERRORS=OFF"
+  ] ++ optionals (!isDarwin) [
+    "-DLLVM_BINUTILS_INCDIR=${libbfd.dev}/include"
+  ] ++ optionals (isDarwin) [
+    "-DLLVM_ENABLE_LIBCXX=ON"
+    "-DCAN_TARGET_i386=false"
+  ] ++ optionals (stdenv.hostPlatform != stdenv.buildPlatform) [
+    "-DCMAKE_CROSSCOMPILING=True"
+    "-DLLVM_TABLEGEN=${buildPackages.llvm_6}/bin/llvm-tblgen"
+  ];
+
+  postBuild = ''
+    rm -fR $out
+  '';
+
+  preCheck = ''
+    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PWD/lib
+  '';
+
+  postInstall = ''
+    mkdir -p $python/share
+    mv $out/share/opt-viewer $python/share/opt-viewer
+  ''
+  + optionalString enableSharedLibraries ''
+    moveToOutput "lib/libLLVM-*" "$lib"
+    moveToOutput "lib/libLLVM${stdenv.hostPlatform.extensions.sharedLibrary}" "$lib"
+    substituteInPlace "$out/lib/cmake/llvm/LLVMExports-${if debugVersion then "debug" else "release"}.cmake" \
+      --replace "\''${_IMPORT_PREFIX}/lib/libLLVM-" "$lib/lib/libLLVM-"
+  ''
+  + optionalString (stdenv.isDarwin && enableSharedLibraries) ''
+    substituteInPlace "$out/lib/cmake/llvm/LLVMExports-${if debugVersion then "debug" else "release"}.cmake" \
+      --replace "\''${_IMPORT_PREFIX}/lib/libLLVM.dylib" "$lib/lib/libLLVM.dylib"
+    ln -s $lib/lib/libLLVM.dylib $lib/lib/libLLVM-${shortVersion}.dylib
+    ln -s $lib/lib/libLLVM.dylib $lib/lib/libLLVM-${release_version}.dylib
+  '';
+
+  doCheck = stdenv.isLinux && (!stdenv.isi686);
+
+  checkTarget = "check-all";
+
+  enableParallelBuilding = true;
+
+  passthru.src = src;
+
+  meta = {
+    description = "Collection of modular and reusable compiler and toolchain technologies";
+    homepage    = http://llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    maintainers = with stdenv.lib.maintainers; [ lovek323 raskin dtzWill ];
+    platforms   = stdenv.lib.platforms.all;
+  };
+} // stdenv.lib.optionalAttrs enableManpages {
+  name = "llvm-manpages-${version}";
+
+  buildPhase = ''
+    make docs-llvm-man
+  '';
+
+  propagatedBuildInputs = [];
+
+  installPhase = ''
+    make -C docs install
+  '';
+
+  outputs = [ "out" ];
+
+  doCheck = false;
+
+  meta.description = "man pages for LLVM ${version}";
+})
diff --git a/nixpkgs/pkgs/development/compilers/llvm/6/openmp.nix b/nixpkgs/pkgs/development/compilers/llvm/6/openmp.nix
new file mode 100644
index 000000000000..908a5f1218f7
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/6/openmp.nix
@@ -0,0 +1,25 @@
+{ stdenv
+, fetch
+, cmake
+, llvm
+, perl
+, version
+}:
+
+stdenv.mkDerivation {
+  name = "openmp-${version}";
+
+  src = fetch "openmp" "0nhwfba9c351r16zgyjyfwdayr98nairky3c2f0b2lc360mwmbv6";
+
+  nativeBuildInputs = [ cmake perl ];
+  buildInputs = [ llvm ];
+
+  enableParallelBuilding = true;
+
+  meta = {
+    description = "Components required to build an executable OpenMP program";
+    homepage    = http://openmp.llvm.org/;
+    license     = stdenv.lib.licenses.mit;
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/6/sanitizers-nongnu.patch b/nixpkgs/pkgs/development/compilers/llvm/6/sanitizers-nongnu.patch
new file mode 100644
index 000000000000..6266eb1958d1
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/6/sanitizers-nongnu.patch
@@ -0,0 +1,413 @@
+From 7b4b3333a2718628b1d510ec1d8438ad67308299 Mon Sep 17 00:00:00 2001
+From: Will Dietz <w@wdtz.org>
+Date: Fri, 29 Jun 2018 09:48:59 -0500
+Subject: [PATCH] Ported to 6.0, taken from gentoo-musl project.
+
+------
+Ported to compiler-rt-sanitizers-5.0.0. Taken from
+
+https://gist.githubusercontent.com/pwaller/2337f3290f12634cad3e3730cff0a6c1/raw/83c87a8585e2f9662494db5662e5361beb093c26/nongnu.patch
+Signed-off-by: Jory A. Pratt <anarchy@gentoo.org>
+
+Taken from gentoo-musl project, with a few additional minor fixes.
+---
+ lib/asan/asan_linux.cc                        |  4 +-
+ lib/interception/interception_linux.cc        |  2 +-
+ lib/interception/interception_linux.h         |  3 +-
+ lib/msan/msan_linux.cc                        |  2 +-
+ lib/sanitizer_common/sanitizer_allocator.cc   |  2 +-
+ .../sanitizer_common_interceptors_ioctl.inc   |  4 +-
+ .../sanitizer_common_syscalls.inc             |  2 +-
+ lib/sanitizer_common/sanitizer_linux.cc       |  8 +++-
+ .../sanitizer_linux_libcdep.cc                | 10 ++---
+ lib/sanitizer_common/sanitizer_platform.h     |  6 +++
+ .../sanitizer_platform_interceptors.h         |  4 +-
+ .../sanitizer_platform_limits_posix.cc        | 37 +++++++++++--------
+ lib/tsan/rtl/tsan_platform_linux.cc           |  2 +-
+ 13 files changed, 51 insertions(+), 35 deletions(-)
+
+diff --git a/lib/asan/asan_linux.cc b/lib/asan/asan_linux.cc
+index 625f32d40..73cf77aca 100644
+--- a/lib/asan/asan_linux.cc
++++ b/lib/asan/asan_linux.cc
+@@ -46,7 +46,7 @@
+ #include <link.h>
+ #endif
+ 
+-#if SANITIZER_ANDROID || SANITIZER_FREEBSD || SANITIZER_SOLARIS
++#if SANITIZER_ANDROID || SANITIZER_FREEBSD || SANITIZER_SOLARIS || SANITIZER_NONGNU
+ #include <ucontext.h>
+ extern "C" void* _DYNAMIC;
+ #elif SANITIZER_NETBSD
+@@ -139,7 +139,7 @@ void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
+   UNIMPLEMENTED();
+ }
+ 
+-#if SANITIZER_ANDROID
++#if SANITIZER_ANDROID || SANITIZER_NONGNU
+ // FIXME: should we do anything for Android?
+ void AsanCheckDynamicRTPrereqs() {}
+ void AsanCheckIncompatibleRT() {}
+diff --git a/lib/interception/interception_linux.cc b/lib/interception/interception_linux.cc
+index c991550a4..2b706418b 100644
+--- a/lib/interception/interception_linux.cc
++++ b/lib/interception/interception_linux.cc
+@@ -43,7 +43,7 @@ bool GetRealFunctionAddress(const char *func_name, uptr *func_addr,
+ }
+ 
+ // Android and Solaris do not have dlvsym
+-#if !SANITIZER_ANDROID && !SANITIZER_SOLARIS
++#if !SANITIZER_ANDROID && !SANITIZER_SOLARIS && !SANITIZER_NONGNU
+ void *GetFuncAddrVer(const char *func_name, const char *ver) {
+   return dlvsym(RTLD_NEXT, func_name, ver);
+ }
+diff --git a/lib/interception/interception_linux.h b/lib/interception/interception_linux.h
+index 98fe51b85..c13302b98 100644
+--- a/lib/interception/interception_linux.h
++++ b/lib/interception/interception_linux.h
+@@ -35,8 +35,7 @@ void *GetFuncAddrVer(const char *func_name, const char *ver);
+       (::__interception::uptr) & (func),                                   \
+       (::__interception::uptr) & WRAP(func))
+ 
+-// Android and Solaris do not have dlvsym
+-#if !SANITIZER_ANDROID && !SANITIZER_SOLARIS
++#if !SANITIZER_ANDROID && !SANITIZER_SOLARIS && !SANITIZER_NONGNU
+ #define INTERCEPT_FUNCTION_VER_LINUX_OR_FREEBSD(func, symver) \
+   (::__interception::real_##func = (func##_f)(                \
+        unsigned long)::__interception::GetFuncAddrVer(#func, symver))
+diff --git a/lib/msan/msan_linux.cc b/lib/msan/msan_linux.cc
+index 4e6321fcb..4d50feb82 100644
+--- a/lib/msan/msan_linux.cc
++++ b/lib/msan/msan_linux.cc
+@@ -13,7 +13,7 @@
+ //===----------------------------------------------------------------------===//
+ 
+ #include "sanitizer_common/sanitizer_platform.h"
+-#if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD
++#if SANITIZER_FREEBSD || (SANITIZER_LINUX && !SANITIZER_NONGNU) || SANITIZER_NETBSD
+ 
+ #include "msan.h"
+ #include "msan_thread.h"
+diff --git a/lib/sanitizer_common/sanitizer_allocator.cc b/lib/sanitizer_common/sanitizer_allocator.cc
+index fc4f7a75a..76cf4f769 100644
+--- a/lib/sanitizer_common/sanitizer_allocator.cc
++++ b/lib/sanitizer_common/sanitizer_allocator.cc
+@@ -23,7 +23,7 @@ namespace __sanitizer {
+ 
+ // ThreadSanitizer for Go uses libc malloc/free.
+ #if SANITIZER_GO || defined(SANITIZER_USE_MALLOC)
+-# if SANITIZER_LINUX && !SANITIZER_ANDROID
++# if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ extern "C" void *__libc_malloc(uptr size);
+ #  if !SANITIZER_GO
+ extern "C" void *__libc_memalign(uptr alignment, uptr size);
+diff --git a/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc b/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
+index 24e7548a5..20259b1d6 100644
+--- a/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
++++ b/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
+@@ -102,7 +102,7 @@ static void ioctl_table_fill() {
+   _(SIOCGETVIFCNT, WRITE, struct_sioc_vif_req_sz);
+ #endif
+ 
+-#if SANITIZER_LINUX
++#if SANITIZER_LINUX && !SANITIZER_NONGNU
+   // Conflicting request ids.
+   // _(CDROMAUDIOBUFSIZ, NONE, 0);
+   // _(SNDCTL_TMR_CONTINUE, NONE, 0);
+@@ -363,7 +363,7 @@ static void ioctl_table_fill() {
+   _(VT_WAITACTIVE, NONE, 0);
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   // _(SIOCDEVPLIP, WRITE, struct_ifreq_sz); // the same as EQL_ENSLAVE
+   _(CYGETDEFTHRESH, WRITE, sizeof(int));
+   _(CYGETDEFTIMEOUT, WRITE, sizeof(int));
+diff --git a/lib/sanitizer_common/sanitizer_common_syscalls.inc b/lib/sanitizer_common/sanitizer_common_syscalls.inc
+index 469c8eb7e..24f87867d 100644
+--- a/lib/sanitizer_common/sanitizer_common_syscalls.inc
++++ b/lib/sanitizer_common/sanitizer_common_syscalls.inc
+@@ -2038,7 +2038,7 @@ POST_SYSCALL(setrlimit)(long res, long resource, void *rlim) {
+   }
+ }
+ 
+-#if !SANITIZER_ANDROID
++#if !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ PRE_SYSCALL(prlimit64)(long pid, long resource, const void *new_rlim,
+                        void *old_rlim) {
+   if (new_rlim) PRE_READ(new_rlim, struct_rlimit64_sz);
+diff --git a/lib/sanitizer_common/sanitizer_linux.cc b/lib/sanitizer_common/sanitizer_linux.cc
+index 6c83e8db4..542c4fe64 100644
+--- a/lib/sanitizer_common/sanitizer_linux.cc
++++ b/lib/sanitizer_common/sanitizer_linux.cc
+@@ -522,13 +522,13 @@ const char *GetEnv(const char *name) {
+ #endif
+ }
+ 
+-#if !SANITIZER_FREEBSD && !SANITIZER_NETBSD
++#if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_NONGNU
+ extern "C" {
+   SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
+ }
+ #endif
+ 
+-#if !SANITIZER_GO && !SANITIZER_FREEBSD && !SANITIZER_NETBSD
++#if (!SANITIZER_GO || SANITIZER_NONGNU) && !SANITIZER_FREEBSD && !SANITIZER_NETBSD
+ static void ReadNullSepFileToArray(const char *path, char ***arr,
+                                    int arr_size) {
+   char *buff;
+@@ -569,6 +569,10 @@ static void GetArgsAndEnv(char ***argv, char ***envp) {
+ #elif SANITIZER_NETBSD
+   *argv = __ps_strings->ps_argvstr;
+   *argv = __ps_strings->ps_envstr;
++#elif SANITIZER_NONGNU
++    static const int kMaxArgv = 2000, kMaxEnvp = 2000;
++    ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
++    ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
+ #else
+ #if !SANITIZER_GO
+   if (&__libc_stack_end) {
+diff --git a/lib/sanitizer_common/sanitizer_linux_libcdep.cc b/lib/sanitizer_common/sanitizer_linux_libcdep.cc
+index 56fdfc870..a932d5db1 100644
+--- a/lib/sanitizer_common/sanitizer_linux_libcdep.cc
++++ b/lib/sanitizer_common/sanitizer_linux_libcdep.cc
+@@ -174,7 +174,7 @@ bool SanitizerGetThreadName(char *name, int max_len) {
+ }
+ 
+ #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO && \
+-    !SANITIZER_NETBSD && !SANITIZER_SOLARIS
++    !SANITIZER_NETBSD && !SANITIZER_SOLARIS && !SANITIZER_NONGNU
+ static uptr g_tls_size;
+ 
+ #ifdef __i386__
+@@ -207,7 +207,7 @@ void InitTlsSize() { }
+ 
+ #if (defined(__x86_64__) || defined(__i386__) || defined(__mips__) \
+     || defined(__aarch64__) || defined(__powerpc64__) || defined(__s390__) \
+-    || defined(__arm__)) && SANITIZER_LINUX && !SANITIZER_ANDROID
++    || defined(__arm__)) && SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ // sizeof(struct pthread) from glibc.
+ static atomic_uintptr_t kThreadDescriptorSize;
+ 
+@@ -391,7 +391,7 @@ int GetSizeFromHdr(struct dl_phdr_info *info, size_t size, void *data) {
+ 
+ #if !SANITIZER_GO
+ static void GetTls(uptr *addr, uptr *size) {
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ # if defined(__x86_64__) || defined(__i386__) || defined(__s390__)
+   *addr = ThreadSelf();
+   *size = GetTlsSize();
+@@ -432,7 +432,7 @@ static void GetTls(uptr *addr, uptr *size) {
+       *addr = (uptr)tcb->tcb_dtv[1];
+     }
+   }
+-#elif SANITIZER_ANDROID
++#elif SANITIZER_ANDROID || SANITIZER_NONGNU
+   *addr = 0;
+   *size = 0;
+ #elif SANITIZER_SOLARIS
+@@ -448,7 +448,7 @@ static void GetTls(uptr *addr, uptr *size) {
+ #if !SANITIZER_GO
+ uptr GetTlsSize() {
+ #if SANITIZER_FREEBSD || SANITIZER_ANDROID || SANITIZER_NETBSD || \
+-    SANITIZER_SOLARIS
++    SANITIZER_SOLARIS || SANITIZER_NONGNU
+   uptr addr, size;
+   GetTls(&addr, &size);
+   return size;
+diff --git a/lib/sanitizer_common/sanitizer_platform.h b/lib/sanitizer_common/sanitizer_platform.h
+index 334903c26..fc2afac2c 100644
+--- a/lib/sanitizer_common/sanitizer_platform.h
++++ b/lib/sanitizer_common/sanitizer_platform.h
+@@ -195,6 +195,12 @@
+ # define SANITIZER_SOLARIS32 0
+ #endif
+ 
++#if defined(__linux__) && !defined(__GLIBC__)
++# define SANITIZER_NONGNU 1
++#else
++# define SANITIZER_NONGNU 0
++#endif
++
+ // By default we allow to use SizeClassAllocator64 on 64-bit platform.
+ // But in some cases (e.g. AArch64's 39-bit address space) SizeClassAllocator64
+ // does not work well and we need to fallback to SizeClassAllocator32.
+diff --git a/lib/sanitizer_common/sanitizer_platform_interceptors.h b/lib/sanitizer_common/sanitizer_platform_interceptors.h
+index b99ac4480..628d226a1 100644
+--- a/lib/sanitizer_common/sanitizer_platform_interceptors.h
++++ b/lib/sanitizer_common/sanitizer_platform_interceptors.h
+@@ -38,7 +38,7 @@
+ # include "sanitizer_platform_limits_solaris.h"
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ # define SI_LINUX_NOT_ANDROID 1
+ #else
+ # define SI_LINUX_NOT_ANDROID 0
+@@ -291,7 +291,7 @@
+   (SI_FREEBSD || SI_MAC || SI_LINUX_NOT_ANDROID)
+ #define SANITIZER_INTERCEPT_ETHER_R (SI_FREEBSD || SI_LINUX_NOT_ANDROID)
+ #define SANITIZER_INTERCEPT_SHMCTL                       \
+-  (SI_NETBSD || SI_SOLARIS || ((SI_FREEBSD || SI_LINUX_NOT_ANDROID) && \
++  (SI_NETBSD || SI_SOLARIS || ((SI_FREEBSD || SI_LINUX_NOT_ANDROID || SANITIZER_NONGNU) && \
+                  SANITIZER_WORDSIZE == 64))  // NOLINT
+ #define SANITIZER_INTERCEPT_RANDOM_R SI_LINUX_NOT_ANDROID
+ #define SANITIZER_INTERCEPT_PTHREAD_ATTR_GET SI_POSIX
+diff --git a/lib/sanitizer_common/sanitizer_platform_limits_posix.cc b/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
+index feb7bad6f..4e89ab2a6 100644
+--- a/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
++++ b/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
+@@ -14,6 +14,9 @@
+ 
+ #include "sanitizer_platform.h"
+ 
++// Workaround musl <--> linux conflicting definition of 'struct sysinfo'
++#define _LINUX_SYSINFO_H
++
+ #if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_MAC
+ // Tests in this file assume that off_t-dependent data structures match the
+ // libc ABI. For example, struct dirent here is what readdir() function (as
+@@ -138,12 +141,14 @@ typedef struct user_fpregs elf_fpregset_t;
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+ #include <glob.h>
+-#include <obstack.h>
++#  if !SANITIZER_NONGNU
++#    include <obstack.h>
++#  endif
+ #include <mqueue.h>
+-#include <net/if_ppp.h>
+-#include <netax25/ax25.h>
+-#include <netipx/ipx.h>
+-#include <netrom/netrom.h>
++#include <linux/if_ppp.h>
++#include <linux/ax25.h>
++#include <linux/ipx.h>
++#include <linux/netrom.h>
+ #if HAVE_RPC_XDR_H
+ # include <rpc/xdr.h>
+ #elif HAVE_TIRPC_RPC_XDR_H
+@@ -251,7 +256,7 @@ namespace __sanitizer {
+   unsigned struct_itimerspec_sz = sizeof(struct itimerspec);
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   // Use pre-computed size of struct ustat to avoid <sys/ustat.h> which
+   // has been removed from glibc 2.28.
+ #if defined(__aarch64__) || defined(__s390x__) || defined (__mips64) \
+@@ -322,7 +327,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(ElfW(Phdr));
+ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+ #endif
+ 
+-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
++#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   int glob_nomatch = GLOB_NOMATCH;
+   int glob_altdirfunc = GLOB_ALTDIRFUNC;
+ #endif
+@@ -416,7 +421,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned struct_termios_sz = sizeof(struct termios);
+   unsigned struct_winsize_sz = sizeof(struct winsize);
+ 
+-#if SANITIZER_LINUX
++#if SANITIZER_LINUX && !SANITIZER_NONGNU
+   unsigned struct_arpreq_sz = sizeof(struct arpreq);
+   unsigned struct_cdrom_msf_sz = sizeof(struct cdrom_msf);
+   unsigned struct_cdrom_multisession_sz = sizeof(struct cdrom_multisession);
+@@ -466,7 +471,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned struct_vt_mode_sz = sizeof(struct vt_mode);
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   unsigned struct_ax25_parms_struct_sz = sizeof(struct ax25_parms_struct);
+   unsigned struct_cyclades_monitor_sz = sizeof(struct cyclades_monitor);
+ #if EV_VERSION > (0x010000)
+@@ -834,7 +839,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned IOCTL_VT_WAITACTIVE = VT_WAITACTIVE;
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   unsigned IOCTL_CYGETDEFTHRESH = CYGETDEFTHRESH;
+   unsigned IOCTL_CYGETDEFTIMEOUT = CYGETDEFTIMEOUT;
+   unsigned IOCTL_CYGETMON = CYGETMON;
+@@ -989,7 +994,7 @@ CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phdr);
+ CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phnum);
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
++#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ CHECK_TYPE_SIZE(glob_t);
+ CHECK_SIZE_AND_OFFSET(glob_t, gl_pathc);
+ CHECK_SIZE_AND_OFFSET(glob_t, gl_pathv);
+@@ -1023,6 +1028,7 @@ CHECK_TYPE_SIZE(iovec);
+ CHECK_SIZE_AND_OFFSET(iovec, iov_base);
+ CHECK_SIZE_AND_OFFSET(iovec, iov_len);
+ 
++#if !SANITIZER_NONGNU
+ CHECK_TYPE_SIZE(msghdr);
+ CHECK_SIZE_AND_OFFSET(msghdr, msg_name);
+ CHECK_SIZE_AND_OFFSET(msghdr, msg_namelen);
+@@ -1036,6 +1042,7 @@ CHECK_TYPE_SIZE(cmsghdr);
+ CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_len);
+ CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_level);
+ CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_type);
++#endif
+ 
+ COMPILER_CHECK(sizeof(__sanitizer_dirent) <= sizeof(dirent));
+ CHECK_SIZE_AND_OFFSET(dirent, d_ino);
+@@ -1138,7 +1145,7 @@ CHECK_SIZE_AND_OFFSET(mntent, mnt_passno);
+ 
+ CHECK_TYPE_SIZE(ether_addr);
+ 
+-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
++#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ CHECK_TYPE_SIZE(ipc_perm);
+ # if SANITIZER_FREEBSD
+ CHECK_SIZE_AND_OFFSET(ipc_perm, key);
+@@ -1199,7 +1206,7 @@ CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_dstaddr);
+ CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_data);
+ #endif
+ 
+-#if SANITIZER_LINUX
++#if SANITIZER_LINUX && !SANITIZER_NONGNU
+ COMPILER_CHECK(sizeof(__sanitizer_mallinfo) == sizeof(struct mallinfo));
+ #endif
+ 
+@@ -1249,7 +1256,7 @@ COMPILER_CHECK(__sanitizer_XDR_DECODE == XDR_DECODE);
+ COMPILER_CHECK(__sanitizer_XDR_FREE == XDR_FREE);
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ COMPILER_CHECK(sizeof(__sanitizer_FILE) <= sizeof(FILE));
+ CHECK_SIZE_AND_OFFSET(FILE, _flags);
+ CHECK_SIZE_AND_OFFSET(FILE, _IO_read_ptr);
+@@ -1268,7 +1275,7 @@ CHECK_SIZE_AND_OFFSET(FILE, _chain);
+ CHECK_SIZE_AND_OFFSET(FILE, _fileno);
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ COMPILER_CHECK(sizeof(__sanitizer__obstack_chunk) <= sizeof(_obstack_chunk));
+ CHECK_SIZE_AND_OFFSET(_obstack_chunk, limit);
+ CHECK_SIZE_AND_OFFSET(_obstack_chunk, prev);
+diff --git a/lib/tsan/rtl/tsan_platform_linux.cc b/lib/tsan/rtl/tsan_platform_linux.cc
+index e14d5f575..389a3bc88 100644
+--- a/lib/tsan/rtl/tsan_platform_linux.cc
++++ b/lib/tsan/rtl/tsan_platform_linux.cc
+@@ -285,7 +285,7 @@ void InitializePlatform() {
+ // This is required to properly "close" the fds, because we do not see internal
+ // closes within glibc. The code is a pure hack.
+ int ExtractResolvFDs(void *state, int *fds, int nfd) {
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   int cnt = 0;
+   struct __res_state *statp = (struct __res_state*)state;
+   for (int i = 0; i < MAXNS && cnt < nfd; i++) {
+-- 
+2.18.0
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/bintools.nix b/nixpkgs/pkgs/development/compilers/llvm/7/bintools.nix
new file mode 100644
index 000000000000..72a2a7331930
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/bintools.nix
@@ -0,0 +1,19 @@
+{ runCommand, stdenv, llvm, lld, version }:
+
+let
+  prefix =
+    if stdenv.hostPlatform != stdenv.targetPlatform
+    then "${stdenv.targetPlatform.config}-"
+    else "";
+in runCommand "llvm-binutils-${version}" { preferLocalBuild = true; } ''
+   mkdir -p $out/bin
+   for prog in ${lld}/bin/*; do
+     ln -s $prog $out/bin/${prefix}$(basename $prog)
+   done
+   for prog in ${llvm}/bin/*; do
+     ln -s $prog $out/bin/${prefix}$(echo $(basename $prog) | sed -e "s|llvm-||")
+     ln -sf $prog $out/bin/${prefix}$(basename $prog)
+   done
+   rm -f $out/bin/${prefix}cat
+   ln -s ${lld}/bin/lld $out/bin/${prefix}ld
+''
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/clang/default.nix b/nixpkgs/pkgs/development/compilers/llvm/7/clang/default.nix
new file mode 100644
index 000000000000..e4252647ce6d
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/clang/default.nix
@@ -0,0 +1,112 @@
+{ stdenv, fetch, cmake, libxml2, llvm, version, clang-tools-extra_src, python
+, fixDarwinDylibNames
+, enableManpages ? false
+, enablePolly ? false # TODO: get this info from llvm (passthru?)
+}:
+
+let
+  self = stdenv.mkDerivation ({
+    name = "clang-${version}";
+
+    unpackPhase = ''
+      unpackFile ${fetch "cfe" "067lwggnbg0w1dfrps790r5l6k8n5zwhlsw7zb6zvmfpwpfn4nx4"}
+      mv cfe-${version}* clang
+      sourceRoot=$PWD/clang
+      unpackFile ${clang-tools-extra_src}
+      mv clang-tools-extra-* $sourceRoot/tools/extra
+    '';
+
+    nativeBuildInputs = [ cmake python ]
+      ++ stdenv.lib.optional enableManpages python.pkgs.sphinx;
+
+    buildInputs = [ libxml2 llvm ]
+      ++ stdenv.lib.optional stdenv.isDarwin fixDarwinDylibNames;
+
+    cmakeFlags = [
+      "-DCMAKE_CXX_FLAGS=-std=c++11"
+    ] ++ stdenv.lib.optionals enableManpages [
+      "-DCLANG_INCLUDE_DOCS=ON"
+      "-DLLVM_ENABLE_SPHINX=ON"
+      "-DSPHINX_OUTPUT_MAN=ON"
+      "-DSPHINX_OUTPUT_HTML=OFF"
+      "-DSPHINX_WARNINGS_AS_ERRORS=OFF"
+    ] ++ stdenv.lib.optionals enablePolly [
+      "-DWITH_POLLY=ON"
+      "-DLINK_POLLY_INTO_TOOLS=ON"
+    ];
+
+    patches = [ ./purity.patch ];
+
+    postPatch = ''
+      sed -i -e 's/DriverArgs.hasArg(options::OPT_nostdlibinc)/true/' \
+             -e 's/Args.hasArg(options::OPT_nostdlibinc)/true/' \
+             lib/Driver/ToolChains/*.cpp
+
+      # Patch for standalone doc building
+      sed -i '1s,^,find_package(Sphinx REQUIRED)\n,' docs/CMakeLists.txt
+    '' + stdenv.lib.optionalString stdenv.hostPlatform.isMusl ''
+      sed -i -e 's/lgcc_s/lgcc_eh/' lib/Driver/ToolChains/*.cpp
+    '' + stdenv.lib.optionalString stdenv.hostPlatform.isDarwin ''
+      substituteInPlace tools/extra/clangd/CMakeLists.txt \
+        --replace "NOT HAVE_CXX_ATOMICS64_WITHOUT_LIB" FALSE
+    '';
+
+    outputs = [ "out" "lib" "python" ];
+
+    # Clang expects to find LLVMgold in its own prefix
+    postInstall = ''
+      if [ -e ${llvm}/lib/LLVMgold.so ]; then
+        ln -sv ${llvm}/lib/LLVMgold.so $out/lib
+      fi
+
+      ln -sv $out/bin/clang $out/bin/cpp
+
+      # Move libclang to 'lib' output
+      moveToOutput "lib/libclang.*" "$lib"
+      substituteInPlace $out/lib/cmake/clang/ClangTargets-release.cmake \
+          --replace "\''${_IMPORT_PREFIX}/lib/libclang." "$lib/lib/libclang."
+
+      mkdir -p $python/bin $python/share/clang/
+      mv $out/bin/{git-clang-format,scan-view} $python/bin
+      if [ -e $out/bin/set-xcode-analyzer ]; then
+        mv $out/bin/set-xcode-analyzer $python/bin
+      fi
+      mv $out/share/clang/*.py $python/share/clang
+      rm $out/bin/c-index-test
+    '';
+
+    enableParallelBuilding = true;
+
+    passthru = {
+      isClang = true;
+      inherit llvm;
+    } // stdenv.lib.optionalAttrs (stdenv.targetPlatform.isLinux || (stdenv.cc.isGNU && stdenv.cc.cc ? gcc)) {
+      gcc = if stdenv.cc.isGNU then stdenv.cc.cc else stdenv.cc.cc.gcc;
+    };
+
+    meta = {
+      description = "A c, c++, objective-c, and objective-c++ frontend for the llvm compiler";
+      homepage    = http://llvm.org/;
+      license     = stdenv.lib.licenses.ncsa;
+      platforms   = stdenv.lib.platforms.all;
+    };
+  } // stdenv.lib.optionalAttrs enableManpages {
+    name = "clang-manpages-${version}";
+
+    buildPhase = ''
+      make docs-clang-man
+    '';
+
+    installPhase = ''
+      mkdir -p $out/share/man/man1
+      # Manually install clang manpage
+      cp docs/man/*.1 $out/share/man/man1/
+    '';
+
+    outputs = [ "out" ];
+
+    doCheck = false;
+
+    meta.description = "man page for Clang ${version}";
+  });
+in self
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/clang/purity.patch b/nixpkgs/pkgs/development/compilers/llvm/7/clang/purity.patch
new file mode 100644
index 000000000000..b30d0d0b5d5b
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/clang/purity.patch
@@ -0,0 +1,30 @@
+From 4add81bba40dcec62c4ea4481be8e35ac53e89d8 Mon Sep 17 00:00:00 2001
+From: Will Dietz <w@wdtz.org>
+Date: Thu, 18 May 2017 11:56:12 -0500
+Subject: [PATCH] "purity" patch for 5.0
+
+---
+ lib/Driver/ToolChains/Gnu.cpp | 7 -------
+ 1 file changed, 7 deletions(-)
+
+diff --git a/lib/Driver/ToolChains/Gnu.cpp b/lib/Driver/ToolChains/Gnu.cpp
+index fe3c0191bb..c6a482bece 100644
+--- a/lib/Driver/ToolChains/Gnu.cpp
++++ b/lib/Driver/ToolChains/Gnu.cpp
+@@ -494,13 +494,6 @@ void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
+   if (!Args.hasArg(options::OPT_static)) {
+     if (Args.hasArg(options::OPT_rdynamic))
+       CmdArgs.push_back("-export-dynamic");
+-
+-    if (!Args.hasArg(options::OPT_shared)) {
+-      const std::string Loader =
+-          D.DyldPrefix + ToolChain.getDynamicLinker(Args);
+-      CmdArgs.push_back("-dynamic-linker");
+-      CmdArgs.push_back(Args.MakeArgString(Loader));
+-    }
+   }
+ 
+   CmdArgs.push_back("-o");
+-- 
+2.11.0
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/compiler-rt-clock_gettime.patch b/nixpkgs/pkgs/development/compilers/llvm/7/compiler-rt-clock_gettime.patch
new file mode 100644
index 000000000000..f9323ed95c05
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/compiler-rt-clock_gettime.patch
@@ -0,0 +1,74 @@
+commit f00c7bccf7955b7dfbb4859fd9019e9eb3349f2d
+Author: Tobias Mayer <tobim@fastmail.fm>
+Date:   Wed Feb 13 12:44:17 2019 +0100
+
+    Provide clock_gettime for xray on macos < 10.12
+
+diff --git a/lib/xray/xray_basic_logging.cc b/lib/xray/xray_basic_logging.cc
+index a46c151af..38aea6932 100644
+--- a/lib/xray/xray_basic_logging.cc
++++ b/lib/xray/xray_basic_logging.cc
+@@ -36,6 +36,29 @@
+ #include "xray_tsc.h"
+ #include "xray_utils.h"
+ 
++#if __MACH__
++#include <mach/clock.h>
++#include <mach/mach.h>
++enum clockid_t {
++    CLOCK_MONOTONIC = REALTIME_CLOCK,
++    CLOCK_REALTIME = REALTIME_CLOCK
++};
++
++int clock_gettime(clockid_t clock_id, struct timespec *ts) {
++  if (ts != NULL) {
++      clock_serv_t cclock;
++      mach_timespec_t mts;
++      host_get_clock_service(mach_host_self(), clock_id, &cclock);
++      clock_get_time(cclock, &mts);
++      mach_port_deallocate(mach_task_self(), cclock);
++      ts->tv_sec = mts.tv_sec;
++      ts->tv_nsec = mts.tv_nsec;
++      return 0;
++  }
++  return -1;
++}
++#endif
++
+ namespace __xray {
+ 
+ SpinMutex LogMutex;
+diff --git a/lib/xray/xray_fdr_logging.cc b/lib/xray/xray_fdr_logging.cc
+index 4b308b27f..1d044c8fd 100644
+--- a/lib/xray/xray_fdr_logging.cc
++++ b/lib/xray/xray_fdr_logging.cc
+@@ -38,6 +38,29 @@
+ #include "xray_tsc.h"
+ #include "xray_utils.h"
+ 
++#if __MACH__
++#include <mach/clock.h>
++#include <mach/mach.h>
++enum clockid_t {
++    CLOCK_MONOTONIC = REALTIME_CLOCK,
++    CLOCK_REALTIME = REALTIME_CLOCK
++};
++
++int clock_gettime(clockid_t clock_id, struct timespec *ts) {
++  if (ts != NULL) {
++      clock_serv_t cclock;
++      mach_timespec_t mts;
++      host_get_clock_service(mach_host_self(), clock_id, &cclock);
++      clock_get_time(cclock, &mts);
++      mach_port_deallocate(mach_task_self(), cclock);
++      ts->tv_sec = mts.tv_sec;
++      ts->tv_nsec = mts.tv_nsec;
++      return 0;
++  }
++  return -1;
++}
++#endif
++
+ namespace __xray {
+ 
+ atomic_sint32_t LoggingStatus = {XRayLogInitStatus::XRAY_LOG_UNINITIALIZED};
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/compiler-rt-codesign.patch b/nixpkgs/pkgs/development/compilers/llvm/7/compiler-rt-codesign.patch
new file mode 100644
index 000000000000..3cc12b94b200
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/compiler-rt-codesign.patch
@@ -0,0 +1,33 @@
+From 3dec5f3475a26aeb4678627795c4b67c6b7b4785 Mon Sep 17 00:00:00 2001
+From: Will Dietz <w@wdtz.org>
+Date: Tue, 19 Sep 2017 13:13:06 -0500
+Subject: [PATCH] remove codesign use on Apple, disable ios sim testing that
+ needs it
+
+---
+ cmake/Modules/AddCompilerRT.cmake |  8 ------
+ test/asan/CMakeLists.txt          | 52 ---------------------------------------
+ test/tsan/CMakeLists.txt          | 47 -----------------------------------
+ 3 files changed, 107 deletions(-)
+
+diff --git a/cmake/Modules/AddCompilerRT.cmake b/cmake/Modules/AddCompilerRT.cmake
+index bc5fb9ff7..b64eb4246 100644
+--- a/cmake/Modules/AddCompilerRT.cmake
++++ b/cmake/Modules/AddCompilerRT.cmake
+@@ -210,14 +210,6 @@ function(add_compiler_rt_runtime name type)
+         set_target_properties(${libname} PROPERTIES IMPORT_PREFIX "")
+         set_target_properties(${libname} PROPERTIES IMPORT_SUFFIX ".lib")
+       endif()
+-      if(APPLE)
+-        # Ad-hoc sign the dylibs
+-        add_custom_command(TARGET ${libname}
+-          POST_BUILD  
+-          COMMAND codesign --sign - $<TARGET_FILE:${libname}>
+-          WORKING_DIRECTORY ${COMPILER_RT_LIBRARY_OUTPUT_DIR}
+-        )
+-      endif()
+     endif()
+     install(TARGETS ${libname}
+       ARCHIVE DESTINATION ${COMPILER_RT_LIBRARY_INSTALL_DIR}
+2.14.1
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/compiler-rt.nix b/nixpkgs/pkgs/development/compilers/llvm/7/compiler-rt.nix
new file mode 100644
index 000000000000..b44ba62ee924
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/compiler-rt.nix
@@ -0,0 +1,61 @@
+{ stdenv, version, fetch, cmake, python, llvm, libcxxabi }:
+stdenv.mkDerivation rec {
+  name = "compiler-rt-${version}";
+  inherit version;
+  src = fetch "compiler-rt" "065ybd8fsc4h2hikbdyricj6pyv4r7r7kpcikhb2y5zf370xybkq";
+
+  nativeBuildInputs = [ cmake python llvm ];
+  buildInputs = stdenv.lib.optional stdenv.hostPlatform.isDarwin libcxxabi;
+
+  cmakeFlags = [
+    "-DCOMPILER_RT_DEFAULT_TARGET_ONLY=ON"
+    "-DCMAKE_C_COMPILER_TARGET=${stdenv.hostPlatform.config}"
+    "-DCMAKE_ASM_COMPILER_TARGET=${stdenv.hostPlatform.config}"
+  ] ++ stdenv.lib.optional (stdenv.hostPlatform != stdenv.buildPlatform) [
+    "-DCMAKE_C_FLAGS=-nodefaultlibs"
+    "-DCMAKE_CXX_COMPILER_WORKS=ON"
+    "-DCOMPILER_RT_BUILD_BUILTINS=ON"
+    "-DCOMPILER_RT_BUILD_SANITIZERS=OFF"
+    "-DCOMPILER_RT_BUILD_XRAY=OFF"
+    "-DCOMPILER_RT_BUILD_LIBFUZZER=OFF"
+    "-DCOMPILER_RT_BUILD_PROFILE=OFF"
+    "-DCOMPILER_RT_BAREMETAL_BUILD=ON"
+  ];
+
+  outputs = [ "out" "dev" ];
+
+  patches = [
+    ./compiler-rt-codesign.patch # Revert compiler-rt commit that makes codesign mandatory
+  ] ++ stdenv.lib.optional stdenv.hostPlatform.isMusl ./sanitizers-nongnu.patch
+    ++ stdenv.lib.optional (stdenv.hostPlatform != stdenv.buildPlatform) ./crtbegin-and-end.patch
+    ++ stdenv.lib.optional stdenv.hostPlatform.isDarwin ./compiler-rt-clock_gettime.patch;
+
+  # TSAN requires XPC on Darwin, which we have no public/free source files for. We can depend on the Apple frameworks
+  # to get it, but they're unfree. Since LLVM is rather central to the stdenv, we patch out TSAN support so that Hydra
+  # can build this. If we didn't do it, basically the entire nixpkgs on Darwin would have an unfree dependency and we'd
+  # get no binary cache for the entire platform. If you really find yourself wanting the TSAN, make this controllable by
+  # a flag and turn the flag off during the stdenv build.
+  postPatch = stdenv.lib.optionalString stdenv.isDarwin ''
+    substituteInPlace cmake/config-ix.cmake \
+      --replace 'set(COMPILER_RT_HAS_TSAN TRUE)' 'set(COMPILER_RT_HAS_TSAN FALSE)'
+  '' + stdenv.lib.optionalString (stdenv.hostPlatform != stdenv.buildPlatform) ''
+    substituteInPlace lib/builtins/int_util.c \
+      --replace "#include <stdlib.h>" ""
+    substituteInPlace lib/builtins/clear_cache.c \
+      --replace "#include <assert.h>" ""
+    substituteInPlace lib/builtins/cpu_model.c \
+      --replace "#include <assert.h>" ""
+  '';
+
+  # Hack around weird upsream RPATH bug
+  postInstall = stdenv.lib.optionalString stdenv.isDarwin ''
+    ln -s "$out/lib"/*/* "$out/lib"
+  '' + stdenv.lib.optionalString (stdenv.hostPlatform != stdenv.buildPlatform) ''
+    ln -s $out/lib/*/clang_rt.crtbegin-*.o $out/lib/linux/crtbegin.o
+    ln -s $out/lib/*/cclang_rt.crtend-*.o $out/lib/linux/crtend.o
+    ln -s $out/lib/*/clang_rt.crtbegin_shared-*.o $out/lib/linux/crtbeginS.o
+    ln -s $out/lib/*/clang_rt.crtend_shared-*.o $out/lib/linux/crtendS.o
+  '';
+
+  enableParallelBuilding = true;
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/crtbegin-and-end.patch b/nixpkgs/pkgs/development/compilers/llvm/7/crtbegin-and-end.patch
new file mode 100644
index 000000000000..e63be181f95c
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/crtbegin-and-end.patch
@@ -0,0 +1,595 @@
+Get crtbegin and crtend without compiler GCC! PR is at https://reviews.llvm.org/D28791
+
+Index: compiler-rt/CMakeLists.txt
+===================================================================
+--- compiler-rt/CMakeLists.txt
++++ compiler-rt/CMakeLists.txt
+@@ -29,6 +29,8 @@
+ 
+ option(COMPILER_RT_BUILD_BUILTINS "Build builtins" ON)
+ mark_as_advanced(COMPILER_RT_BUILD_BUILTINS)
++option(COMPILER_RT_BUILD_CRT "Build crtbegin.o/crtend.o" ON)
++mark_as_advanced(COMPILER_RT_BUILD_CRT)
+ option(COMPILER_RT_BUILD_SANITIZERS "Build sanitizers" ON)
+ mark_as_advanced(COMPILER_RT_BUILD_SANITIZERS)
+ option(COMPILER_RT_BUILD_XRAY "Build xray" ON)
+Index: compiler-rt/cmake/Modules/AddCompilerRT.cmake
+===================================================================
+--- compiler-rt/cmake/Modules/AddCompilerRT.cmake
++++ compiler-rt/cmake/Modules/AddCompilerRT.cmake
+@@ -132,7 +132,7 @@
+ # Adds static or shared runtime for a list of architectures and operating
+ # systems and puts it in the proper directory in the build and install trees.
+ # add_compiler_rt_runtime(<name>
+-#                         {STATIC|SHARED}
++#                         {OBJECT|STATIC|SHARED}
+ #                         ARCHS <architectures>
+ #                         OS <os list>
+ #                         SOURCES <source files>
+@@ -144,8 +144,8 @@
+ #                         PARENT_TARGET <convenience parent target>
+ #                         ADDITIONAL_HEADERS <header files>)
+ function(add_compiler_rt_runtime name type)
+-  if(NOT type MATCHES "^(STATIC|SHARED)$")
+-    message(FATAL_ERROR "type argument must be STATIC or SHARED")
++  if(NOT type MATCHES "^(OBJECT|STATIC|SHARED)$")
++    message(FATAL_ERROR "type argument must be OBJECT, STATIC or SHARED")
+     return()
+   endif()
+   cmake_parse_arguments(LIB
+@@ -204,7 +204,10 @@
+         message(FATAL_ERROR "Architecture ${arch} can't be targeted")
+         return()
+       endif()
+-      if(type STREQUAL "STATIC")
++      if(type STREQUAL "OBJECT")
++        set(libname "${name}-${arch}")
++        set(output_name_${libname} ${libname}${COMPILER_RT_OS_SUFFIX})
++      elseif(type STREQUAL "STATIC")
+         set(libname "${name}-${arch}")
+         set_output_name(output_name_${libname} ${name} ${arch})
+       else()
+@@ -270,12 +273,34 @@
+       set(COMPONENT_OPTION COMPONENT ${libname})
+     endif()
+ 
+-    add_library(${libname} ${type} ${sources_${libname}})
+-    set_target_compile_flags(${libname} ${extra_cflags_${libname}})
+-    set_target_link_flags(${libname} ${extra_link_flags_${libname}})
+-    set_property(TARGET ${libname} APPEND PROPERTY
+-                COMPILE_DEFINITIONS ${LIB_DEFS})
+-    set_target_output_directories(${libname} ${output_dir_${libname}})
++    if(type STREQUAL "OBJECT")
++      string(TOUPPER ${CMAKE_BUILD_TYPE} config)
++      get_property(cflags SOURCE ${sources_${libname}} PROPERTY COMPILE_FLAGS)
++      separate_arguments(cflags)
++      add_custom_command(
++          OUTPUT ${output_dir_${libname}}/${libname}.o
++          COMMAND ${CMAKE_C_COMPILER} ${sources_${libname}} ${cflags} ${extra_cflags_${libname}} -c -o ${output_dir_${libname}}/${libname}.o
++          DEPENDS ${sources_${libname}}
++          COMMENT "Building C object ${libname}.o")
++      add_custom_target(${libname} DEPENDS ${output_dir_${libname}}/${libname}.o)
++      install(FILES ${output_dir_${libname}}/${libname}.o
++        DESTINATION ${install_dir_${libname}}
++        ${COMPONENT_OPTION})
++    else()
++      add_library(${libname} ${type} ${sources_${libname}})
++      set_target_compile_flags(${libname} ${extra_cflags_${libname}})
++      set_target_link_flags(${libname} ${extra_link_flags_${libname}})
++      set_property(TARGET ${libname} APPEND PROPERTY
++                   COMPILE_DEFINITIONS ${LIB_DEFS})
++      set_target_output_directories(${libname} ${output_dir_${libname}})
++      install(TARGETS ${libname}
++        ARCHIVE DESTINATION ${install_dir_${libname}}
++                ${COMPONENT_OPTION}
++        LIBRARY DESTINATION ${install_dir_${libname}}
++                ${COMPONENT_OPTION}
++        RUNTIME DESTINATION ${install_dir_${libname}}
++                ${COMPONENT_OPTION})
++    endif()
+     set_target_properties(${libname} PROPERTIES
+         OUTPUT_NAME ${output_name_${libname}})
+     set_target_properties(${libname} PROPERTIES FOLDER "Compiler-RT Runtime")
+@@ -299,13 +324,6 @@
+         )
+       endif()
+     endif()
+-    install(TARGETS ${libname}
+-      ARCHIVE DESTINATION ${install_dir_${libname}}
+-              ${COMPONENT_OPTION}
+-      LIBRARY DESTINATION ${install_dir_${libname}}
+-              ${COMPONENT_OPTION}
+-      RUNTIME DESTINATION ${install_dir_${libname}}
+-              ${COMPONENT_OPTION})
+ 
+     # We only want to generate per-library install targets if you aren't using
+     # an IDE because the extra targets get cluttered in IDEs.
+Index: compiler-rt/cmake/config-ix.cmake
+===================================================================
+--- compiler-rt/cmake/config-ix.cmake
++++ compiler-rt/cmake/config-ix.cmake
+@@ -227,6 +227,7 @@
+     ${ARM32} ${ARM64} ${MIPS32} ${MIPS64} ${S390X})
+ set(ALL_ASAN_SUPPORTED_ARCH ${X86} ${X86_64} ${ARM32} ${ARM64}
+     ${MIPS32} ${MIPS64} ${PPC64} ${S390X})
++set(ALL_CRT_SUPPORTED_ARCH ${X86} ${X86_64} ${ARM32} ${ARM64})
+ set(ALL_DFSAN_SUPPORTED_ARCH ${X86_64} ${MIPS64} ${ARM64})
+ set(ALL_FUZZER_SUPPORTED_ARCH ${X86_64} ${ARM64})
+ 
+@@ -474,6 +475,7 @@
+     SANITIZER_COMMON_SUPPORTED_ARCH)
+ 
+ else()
++  filter_available_targets(CRT_SUPPORTED_ARCH ${ALL_CRT_SUPPORTED_ARCH})
+   # Architectures supported by compiler-rt libraries.
+   filter_available_targets(SANITIZER_COMMON_SUPPORTED_ARCH
+     ${ALL_SANITIZER_COMMON_SUPPORTED_ARCH})
+@@ -563,6 +565,12 @@
+ 
+ # TODO: Add builtins support.
+ 
++if (CRT_SUPPORTED_ARCH AND OS_NAME MATCHES "Linux")
++  set(COMPILER_RT_HAS_CRT TRUE)
++else()
++  set(COMPILER_RT_HAS_CRT FALSE)
++endif()
++
+ if (COMPILER_RT_HAS_SANITIZER_COMMON AND DFSAN_SUPPORTED_ARCH AND
+     OS_NAME MATCHES "Linux")
+   set(COMPILER_RT_HAS_DFSAN TRUE)
+Index: compiler-rt/lib/CMakeLists.txt
+===================================================================
+--- compiler-rt/lib/CMakeLists.txt
++++ compiler-rt/lib/CMakeLists.txt
+@@ -17,6 +17,10 @@
+   add_subdirectory(builtins)
+ endif()
+ 
++if(COMPILER_RT_BUILD_CRT)
++  add_subdirectory(crt)
++endif()
++
+ function(compiler_rt_build_runtime runtime)
+   string(TOUPPER ${runtime} runtime_uppercase)
+   if(COMPILER_RT_HAS_${runtime_uppercase})
+Index: compiler-rt/lib/crt/CMakeLists.txt
+===================================================================
+--- /dev/null
++++ compiler-rt/lib/crt/CMakeLists.txt
+@@ -0,0 +1,102 @@
++add_compiler_rt_component(crt)
++
++function(check_cxx_section_exists section output)
++  cmake_parse_arguments(ARG "" "" "SOURCE;FLAGS" ${ARGN})
++  if(NOT ARG_SOURCE)
++    set(ARG_SOURCE "int main() { return 0; }\n")
++  endif()
++
++  string(RANDOM TARGET_NAME)
++  set(TARGET_NAME "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/cmTC_${TARGET_NAME}.dir")
++  file(MAKE_DIRECTORY ${TARGET_NAME})
++
++  file(WRITE "${TARGET_NAME}/CheckSectionExists.c" "${ARG_SOURCE}\n")
++
++  string(REGEX MATCHALL "<[A-Za-z0-9_]*>" substitutions
++         ${CMAKE_C_COMPILE_OBJECT})
++
++  set(try_compile_flags "${ARG_FLAGS}")
++  if(CMAKE_C_COMPILER_ID MATCHES Clang AND CMAKE_C_COMPILER_TARGET)
++    list(APPEND try_compile_flags "-target ${CMAKE_C_COMPILER_TARGET}")
++  endif()
++
++  string(REPLACE ";" " " extra_flags "${try_compile_flags}")
++
++  set(test_compile_command "${CMAKE_C_COMPILE_OBJECT}")
++  foreach(substitution ${substitutions})
++    if(substitution STREQUAL "<CMAKE_C_COMPILER>")
++      string(REPLACE "<CMAKE_C_COMPILER>"
++             "${CMAKE_C_COMPILER}" test_compile_command ${test_compile_command})
++    elseif(substitution STREQUAL "<OBJECT>")
++      string(REPLACE "<OBJECT>" "${TARGET_NAME}/CheckSectionExists.o"
++             test_compile_command ${test_compile_command})
++    elseif(substitution STREQUAL "<SOURCE>")
++      string(REPLACE "<SOURCE>" "${TARGET_NAME}/CheckSectionExists.c"
++             test_compile_command ${test_compile_command})
++    elseif(substitution STREQUAL "<FLAGS>")
++      string(REPLACE "<FLAGS>" "${CMAKE_C_FLAGS} ${extra_flags}"
++             test_compile_command ${test_compile_command})
++    else()
++      string(REPLACE "${substitution}" "" test_compile_command
++             ${test_compile_command})
++    endif()
++  endforeach()
++
++  string(REPLACE " " ";" test_compile_command "${test_compile_command}")
++
++  execute_process(
++    COMMAND ${test_compile_command}
++    RESULT_VARIABLE TEST_RESULT
++    OUTPUT_VARIABLE TEST_OUTPUT
++    ERROR_VARIABLE TEST_ERROR
++  )
++
++  execute_process(
++    COMMAND ${CMAKE_OBJDUMP} -h "${TARGET_NAME}/CheckSectionExists.o"
++    RESULT_VARIABLE CHECK_RESULT
++    OUTPUT_VARIABLE CHECK_OUTPUT
++    ERROR_VARIABLE CHECK_ERROR
++  )
++  string(FIND "${CHECK_OUTPUT}" "${section}" SECTION_FOUND)
++
++  if(NOT SECTION_FOUND EQUAL -1)
++    set(${output} TRUE PARENT_SCOPE)
++  else()
++    set(${output} FALSE PARENT_SCOPE)
++  endif()
++
++  file(REMOVE_RECURSE ${TARGET_NAME})
++endfunction()
++
++check_cxx_section_exists(".init_array" COMPILER_RT_HAS_INITFINI_ARRAY
++  SOURCE "__attribute__((constructor)) void f() {}\nint main() { return 0; }\n")
++
++append_list_if(COMPILER_RT_HAS_INITFINI_ARRAY -DCRT_HAS_INITFINI_ARRAY CRT_CFLAGS)
++append_list_if(COMPILER_RT_HAS_FPIC_FLAG -fPIC CRT_CFLAGS)
++
++foreach(arch ${CRT_SUPPORTED_ARCH})
++  add_compiler_rt_runtime(clang_rt.crtbegin
++    OBJECT
++    ARCHS ${arch}
++    SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/crtbegin.c
++    CFLAGS ${CRT_CFLAGS}
++    PARENT_TARGET crt)
++  add_compiler_rt_runtime(clang_rt.crtbegin_shared
++    OBJECT
++    ARCHS ${arch}
++    SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/crtbegin.c
++    CFLAGS ${CRT_CFLAGS} -DCRT_SHARED
++    PARENT_TARGET crt)
++  add_compiler_rt_runtime(clang_rt.crtend
++    OBJECT
++    ARCHS ${arch}
++    SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/crtend.c
++    CFLAGS ${CRT_CFLAGS}
++    PARENT_TARGET crt)
++  add_compiler_rt_runtime(clang_rt.crtend_shared
++    OBJECT
++    ARCHS ${arch}
++    SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/crtend.c
++    CFLAGS ${CRT_CFLAGS} -DCRT_SHARED
++    PARENT_TARGET crt)
++endforeach()
+Index: compiler-rt/lib/crt/crtbegin.c
+===================================================================
+--- /dev/null
++++ compiler-rt/lib/crt/crtbegin.c
+@@ -0,0 +1,108 @@
++/* ===-- crtbegin.c - Start of constructors and destructors ----------------===
++ *
++ *      	       The LLVM Compiler Infrastructure
++ *
++ * This file is dual licensed under the MIT and the University of Illinois Open
++ * Source Licenses. See LICENSE.TXT for details.
++ *
++ * ===----------------------------------------------------------------------===
++ */
++
++#include <stddef.h>
++
++__attribute__((visibility("hidden")))
++#ifdef CRT_SHARED
++void *__dso_handle = &__dso_handle;
++#else
++void *__dso_handle = (void *)0;
++#endif
++
++static long __EH_FRAME_LIST__[]
++    __attribute__((section(".eh_frame"), aligned(sizeof(void *)))) = {};
++
++extern void __register_frame_info(const void *, void *) __attribute__((weak));
++extern void *__deregister_frame_info(const void *) __attribute__((weak));
++
++#ifndef CRT_HAS_INITFINI_ARRAY
++typedef void (*fp)(void);
++
++static fp __CTOR_LIST__[]
++    __attribute__((section(".ctors"), aligned(sizeof(fp)), used)) = {(fp)-1};
++extern fp __CTOR_LIST_END__[];
++#endif
++
++#ifdef CRT_SHARED
++extern void __cxa_finalize(void *) __attribute__((weak));
++#endif
++
++static void __attribute__((used)) __do_init() {
++  static _Bool __initialized;
++  if (__builtin_expect(__initialized, 0))
++    return;
++  __initialized = 1;
++
++  static struct { void *p[8]; } __object;
++  if (__register_frame_info)
++    __register_frame_info(__EH_FRAME_LIST__, &__object);
++
++#ifndef CRT_HAS_INITFINI_ARRAY
++  const size_t n = __CTOR_LIST_END__ - __CTOR_LIST__ - 1;
++  for (size_t i = n; i >= 1; i--) __CTOR_LIST__[i]();
++#endif
++}
++
++#ifdef CRT_HAS_INITFINI_ARRAY
++__attribute__((section(".init_array"),
++               used)) static void (*__init)(void) = __do_init;
++#else  // CRT_HAS_INITFINI_ARRAY
++#if defined(__i386__) || defined(__x86_64__)
++asm(".pushsection .init,\"ax\",@progbits\n\t"
++    "call " __USER_LABEL_PREFIX__ "__do_init\n\t"
++    ".popsection");
++#elif defined(__arm__)
++asm(".pushsection .init,\"ax\",%progbits\n\t"
++    "bl " __USER_LABEL_PREFIX__ "__do_init\n\t"
++    ".popsection");
++#endif  // CRT_HAS_INITFINI_ARRAY
++#endif
++
++#ifndef CRT_HAS_INITFINI_ARRAY
++static fp __DTOR_LIST__[]
++    __attribute__((section(".dtors"), aligned(sizeof(fp)), used)) = {(fp)-1};
++extern fp __DTOR_LIST_END__[];
++#endif
++
++static void __attribute__((used)) __do_fini() {
++  static _Bool __finalized;
++  if (__builtin_expect(__finalized, 0))
++    return;
++  __finalized = 1;
++
++#ifdef CRT_SHARED
++  if (__cxa_finalize)
++    __cxa_finalize(__dso_handle);
++#endif
++
++#ifndef CRT_HAS_INITFINI_ARRAY
++  if (__deregister_frame_info)
++    __deregister_frame_info(__EH_FRAME_LIST__);
++
++  const size_t n = __DTOR_LIST_END__ - __DTOR_LIST__ - 1;
++  for (size_t i = 1; i < n; i++) __DTOR_LIST__[i]();
++#endif
++}
++
++#ifdef CRT_HAS_INITFINI_ARRAY
++__attribute__((section(".fini_array"),
++               used)) static void (*__fini)(void) = __do_fini;
++#else  // CRT_HAS_INITFINI_ARRAY
++#if defined(__i386__) || defined(__x86_64__)
++asm(".pushsection .fini,\"ax\",@progbits\n\t"
++    "call " __USER_LABEL_PREFIX__ "__do_fini\n\t"
++    ".popsection");
++#elif defined(__arm__)
++asm(".pushsection .fini,\"ax\",%progbits\n\t"
++    "bl " __USER_LABEL_PREFIX__ "__do_fini\n\t"
++    ".popsection");
++#endif
++#endif  // CRT_HAS_INIT_FINI_ARRAY
+Index: compiler-rt/lib/crt/crtend.c
+===================================================================
+--- /dev/null
++++ compiler-rt/lib/crt/crtend.c
+@@ -0,0 +1,24 @@
++/* ===-- crtend.c - End of constructors and destructors --------------------===
++ *
++ *      	       The LLVM Compiler Infrastructure
++ *
++ * This file is dual licensed under the MIT and the University of Illinois Open
++ * Source Licenses. See LICENSE.TXT for details.
++ *
++ * ===----------------------------------------------------------------------===
++ */
++
++#include <stdint.h>
++
++// Put 4-byte zero which is the length field in FDE at the end as a terminator.
++const int32_t __EH_FRAME_LIST_END__[]
++    __attribute__((section(".eh_frame"), aligned(sizeof(int32_t)),
++                   visibility("hidden"), used)) = {0};
++
++#ifndef CRT_HAS_INITFINI_ARRAY
++typedef void (*fp)(void);
++fp __CTOR_LIST_END__[]
++    __attribute__((section(".ctors"), visibility("hidden"), used)) = {0};
++fp __DTOR_LIST_END__[]
++    __attribute__((section(".dtors"), visibility("hidden"), used)) = {0};
++#endif
+Index: compiler-rt/test/CMakeLists.txt
+===================================================================
+--- compiler-rt/test/CMakeLists.txt
++++ compiler-rt/test/CMakeLists.txt
+@@ -73,6 +73,9 @@
+   if(COMPILER_RT_BUILD_XRAY)
+     compiler_rt_test_runtime(xray)
+   endif()
++  if(COMPILER_RT_HAS_CRT)
++    add_subdirectory(crt)
++  endif()
+   # ShadowCallStack does not yet provide a runtime with compiler-rt, the tests
+   # include their own minimal runtime
+   add_subdirectory(shadowcallstack)
+Index: compiler-rt/test/crt/CMakeLists.txt
+===================================================================
+--- /dev/null
++++ compiler-rt/test/crt/CMakeLists.txt
+@@ -0,0 +1,31 @@
++set(CRT_LIT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
++
++set(CRT_TESTSUITES)
++
++set(CRT_TEST_DEPS "")
++
++if(NOT COMPILER_RT_STANDALONE_BUILD AND COMPILER_RT_BUILD_CRT AND
++   COMPILER_RT_HAS_CRT)
++  list(APPEND CRT_TEST_DEPS crt)
++endif()
++
++set(CRT_TEST_ARCH ${CRT_SUPPORTED_ARCH})
++if (COMPILER_RT_BUILD_CRT AND COMPILER_RT_HAS_CRT)
++  foreach(arch ${CRT_TEST_ARCH})
++    set(CRT_TEST_TARGET_ARCH ${arch})
++    string(TOLOWER "-${arch}-${OS_NAME}" CRT_TEST_CONFIG_SUFFIX)
++    get_test_cc_for_arch(${arch} CRT_TEST_TARGET_CC CRT_TEST_TARGET_CFLAGS)
++    string(TOUPPER ${arch} ARCH_UPPER_CASE)
++    set(CONFIG_NAME ${ARCH_UPPER_CASE}${OS_NAME}Config)
++
++    configure_lit_site_cfg(
++      ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in
++      ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/lit.site.cfg)
++    list(APPEND CRT_TESTSUITES ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME})
++  endforeach()
++endif()
++
++add_lit_testsuite(check-crt "Running the CRT tests"
++  ${CRT_TESTSUITES}
++  DEPENDS ${CRT_TEST_DEPS})
++set_target_properties(check-crt PROPERTIES FOLDER "Compiler-RT Misc")
+Index: compiler-rt/test/crt/dso_handle.cpp
+===================================================================
+--- /dev/null
++++ compiler-rt/test/crt/dso_handle.cpp
+@@ -0,0 +1,33 @@
++// RUN: %clangxx -g -DCRT_SHARED -c %s -fPIC -o %tshared.o
++// RUN: %clangxx -g -c %s -fPIC -o %t.o
++// RUN: %clangxx -g -shared -o %t.so -nostdlib %crti %shared_crtbegin %tshared.o %libstdcxx -lc -lm -lgcc_s %shared_crtend %crtn
++// RUN: %clangxx -g -o %t -nostdlib %crt1 %crti %crtbegin %t.o %libstdcxx -lc -lm %libgcc %t.so %crtend %crtn
++// RUN: %run %t 2>&1 | FileCheck %s
++
++#include <stdio.h>
++
++// CHECK: 1
++// CHECK-NEXT: ~A()
++
++#ifdef CRT_SHARED
++bool G;
++void C() {
++  printf("%d\n", G);
++}
++
++struct A {
++  A() { G = true; }
++  ~A() {
++    printf("~A()\n");
++  }
++};
++
++A a;
++#else
++void C();
++
++int main() {
++  C();
++  return 0;
++}
++#endif
+Index: compiler-rt/test/crt/lit.cfg
+===================================================================
+--- /dev/null
++++ compiler-rt/test/crt/lit.cfg
+@@ -0,0 +1,80 @@
++# -*- Python -*-
++
++import os
++import subprocess
++
++# Setup config name.
++config.name = 'CRT' + config.name_suffix
++
++# Setup source root.
++config.test_source_root = os.path.dirname(__file__)
++
++
++def get_library_path(file):
++    cmd = subprocess.Popen([config.clang.strip(),
++                            config.target_cflags.strip(),
++                            '-print-file-name=%s' % file],
++                           stdout=subprocess.PIPE,
++                           env=config.environment)
++    if not cmd.stdout:
++      lit_config.fatal("Couldn't find the library path for '%s'" % file)
++    dir = cmd.stdout.read().strip()
++    if sys.platform in ['win32'] and execute_external:
++        # Don't pass dosish path separator to msys bash.exe.
++        dir = dir.replace('\\', '/')
++    # Ensure the result is an ascii string, across Python2.5+ - Python3.
++    return str(dir.decode('ascii'))
++
++
++def get_libgcc_file_name():
++    cmd = subprocess.Popen([config.clang.strip(),
++                            config.target_cflags.strip(),
++                            '-print-libgcc-file-name'],
++                           stdout=subprocess.PIPE,
++                           env=config.environment)
++    if not cmd.stdout:
++      lit_config.fatal("Couldn't find the library path for '%s'" % file)
++    dir = cmd.stdout.read().strip()
++    if sys.platform in ['win32'] and execute_external:
++        # Don't pass dosish path separator to msys bash.exe.
++        dir = dir.replace('\\', '/')
++    # Ensure the result is an ascii string, across Python2.5+ - Python3.
++    return str(dir.decode('ascii'))
++
++
++def build_invocation(compile_flags):
++    return ' ' + ' '.join([config.clang] + compile_flags) + ' '
++
++
++# Setup substitutions.
++config.substitutions.append(
++    ('%clang ', build_invocation([config.target_cflags])))
++config.substitutions.append(
++    ('%clangxx ',
++     build_invocation(config.cxx_mode_flags + [config.target_cflags])))
++
++base_lib = os.path.join(
++    config.compiler_rt_libdir, "clang_rt.%%s-%s.o" % config.target_arch)
++config.substitutions.append(('%crtbegin', base_lib % "crtbegin"))
++config.substitutions.append(('%shared_crtbegin', base_lib % "crtbegin_shared"))
++config.substitutions.append(('%crtend', base_lib % "crtend"))
++config.substitutions.append(('%shared_crtend', base_lib % "crtend_shared"))
++
++config.substitutions.append(
++    ('%crt1', get_library_path('crt1.o')))
++config.substitutions.append(
++    ('%crti', get_library_path('crti.o')))
++config.substitutions.append(
++    ('%crtn', get_library_path('crtn.o')))
++
++config.substitutions.append(
++    ('%libgcc', get_libgcc_file_name()))
++
++config.substitutions.append(
++    ('%libstdcxx', '-l' + config.sanitizer_cxx_lib.lstrip('lib')))
++
++# Default test suffixes.
++config.suffixes = ['.c', '.cc', '.cpp']
++
++if config.host_os not in ['Linux']:
++    config.unsupported = True
+Index: compiler-rt/test/crt/lit.site.cfg.in
+===================================================================
+--- /dev/null
++++ compiler-rt/test/crt/lit.site.cfg.in
+@@ -0,0 +1,14 @@
++@LIT_SITE_CFG_IN_HEADER@
++
++# Tool-specific config options.
++config.name_suffix = "@CRT_TEST_CONFIG_SUFFIX@"
++config.crt_lit_source_dir = "@CRT_LIT_SOURCE_DIR@"
++config.target_cflags = "@CRT_TEST_TARGET_CFLAGS@"
++config.target_arch = "@CRT_TEST_TARGET_ARCH@"
++config.sanitizer_cxx_lib = "@SANITIZER_TEST_CXX_LIBNAME@"
++
++# Load common config for all compiler-rt lit tests
++lit_config.load_config(config, "@COMPILER_RT_BINARY_DIR@/test/lit.common.configured")
++
++# Load tool-specific config that would do the real work.
++lit_config.load_config(config, "@CRT_LIT_SOURCE_DIR@/lit.cfg")
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/default.nix b/nixpkgs/pkgs/development/compilers/llvm/7/default.nix
new file mode 100644
index 000000000000..060bef69bc15
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/default.nix
@@ -0,0 +1,149 @@
+{ lowPrio, newScope, pkgs, stdenv, cmake, libstdcxxHook
+, libxml2, python, isl, fetchurl, overrideCC, wrapCCWith, wrapBintoolsWith
+, buildLlvmTools # tools, but from the previous stage, for cross
+, targetLlvmLibraries # libraries, but from the next stage, for cross
+}:
+
+let
+  release_version = "7.0.1";
+  version = release_version; # differentiating these is important for rc's
+
+  fetch = name: sha256: fetchurl {
+    url = "https://releases.llvm.org/${release_version}/${name}-${version}.src.tar.xz";
+    inherit sha256;
+  };
+
+  clang-tools-extra_src = fetch "clang-tools-extra" "1v9vc7id1761qm7mywlknsp810232iwyz8rd4y5km4h7pg9cg4sc";
+
+  tools = stdenv.lib.makeExtensible (tools: let
+    callPackage = newScope (tools // { inherit stdenv cmake libxml2 python isl release_version version fetch; });
+    mkExtraBuildCommands = cc: ''
+      rsrc="$out/resource-root"
+      mkdir "$rsrc"
+      ln -s "${cc}/lib/clang/${release_version}/include" "$rsrc"
+      ln -s "${targetLlvmLibraries.compiler-rt.out}/lib" "$rsrc/lib"
+      echo "-resource-dir=$rsrc" >> $out/nix-support/cc-cflags
+    '' + stdenv.lib.optionalString (stdenv.targetPlatform.isLinux && tools.clang-unwrapped ? gcc) ''
+      echo "--gcc-toolchain=${tools.clang-unwrapped.gcc}" >> $out/nix-support/cc-cflags
+    '';
+  in {
+
+    llvm = callPackage ./llvm.nix { };
+    llvm-polly = callPackage ./llvm.nix { enablePolly = true; };
+
+    clang-unwrapped = callPackage ./clang {
+      inherit clang-tools-extra_src;
+    };
+    clang-polly-unwrapped = callPackage ./clang {
+      inherit clang-tools-extra_src;
+      llvm = tools.llvm-polly;
+      enablePolly = true;
+    };
+
+    llvm-manpages = lowPrio (tools.llvm.override {
+      enableManpages = true;
+      python = pkgs.python;  # don't use python-boot
+    });
+
+    clang-manpages = lowPrio (tools.clang-unwrapped.override {
+      enableManpages = true;
+      python = pkgs.python;  # don't use python-boot
+    });
+
+    libclang = tools.clang-unwrapped.lib;
+
+    clang = if stdenv.cc.isGNU then tools.libstdcxxClang else tools.libcxxClang;
+
+    libstdcxxClang = wrapCCWith rec {
+      cc = tools.clang-unwrapped;
+      extraPackages = [
+        libstdcxxHook
+        targetLlvmLibraries.compiler-rt
+      ];
+      extraBuildCommands = mkExtraBuildCommands cc;
+    };
+
+    libcxxClang = wrapCCWith rec {
+      cc = tools.clang-unwrapped;
+      libcxx = targetLlvmLibraries.libcxx;
+      extraPackages = [
+        targetLlvmLibraries.libcxx
+        targetLlvmLibraries.libcxxabi
+        targetLlvmLibraries.compiler-rt
+      ];
+      extraBuildCommands = mkExtraBuildCommands cc;
+    };
+
+    lld = callPackage ./lld.nix {};
+
+    lldb = callPackage ./lldb.nix {};
+
+    bintools = callPackage ./bintools.nix {};
+
+    lldClang = wrapCCWith rec {
+      cc = tools.clang-unwrapped;
+      bintools = wrapBintoolsWith {
+        inherit (tools) bintools;
+      };
+      extraPackages = [
+        # targetLlvmLibraries.libcxx
+        # targetLlvmLibraries.libcxxabi
+        targetLlvmLibraries.compiler-rt
+      ];
+      extraBuildCommands = ''
+        echo "-target ${stdenv.targetPlatform.config} -rtlib=compiler-rt" >> $out/nix-support/cc-cflags
+      '' + mkExtraBuildCommands cc;
+    };
+
+    lldClangNoLibc = wrapCCWith rec {
+      cc = tools.clang-unwrapped;
+      bintools = wrapBintoolsWith {
+        inherit (tools) bintools;
+        libc = null;
+      };
+      extraPackages = [
+        # targetLlvmLibraries.libcxx
+        # targetLlvmLibraries.libcxxabi
+        targetLlvmLibraries.compiler-rt
+      ];
+      extraBuildCommands = ''
+        echo "-target ${stdenv.targetPlatform.config} -rtlib=compiler-rt" >> $out/nix-support/cc-cflags
+      '' + mkExtraBuildCommands cc;
+    };
+
+    lldClangNoCompilerRt = wrapCCWith rec {
+      cc = tools.clang-unwrapped;
+      bintools = wrapBintoolsWith {
+        inherit (tools) bintools;
+        libc = null;
+      };
+      extraPackages = [ ];
+      extraBuildCommands = ''
+        echo "-nostartfiles -target ${stdenv.targetPlatform.config}" >> $out/nix-support/cc-cflags
+      '';
+    };
+
+  });
+
+  libraries = stdenv.lib.makeExtensible (libraries: let
+    callPackage = newScope (libraries // buildLlvmTools // { inherit stdenv cmake libxml2 python isl release_version version fetch; });
+  in {
+
+    compiler-rt = callPackage ./compiler-rt.nix {
+      stdenv = if stdenv.hostPlatform.useLLVM or false
+               then overrideCC stdenv buildLlvmTools.lldClangNoCompilerRt
+               else stdenv;
+    };
+
+    stdenv = overrideCC stdenv buildLlvmTools.clang;
+
+    libcxxStdenv = overrideCC stdenv buildLlvmTools.libcxxClang;
+
+    libcxx = callPackage ./libc++ {};
+
+    libcxxabi = callPackage ./libc++abi.nix {};
+
+    openmp = callPackage ./openmp.nix {};
+  });
+
+in { inherit tools libraries; } // libraries // tools
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/libc++/default.nix b/nixpkgs/pkgs/development/compilers/llvm/7/libc++/default.nix
new file mode 100644
index 000000000000..d372984dac7c
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/libc++/default.nix
@@ -0,0 +1,50 @@
+{ lib, stdenv, fetch, cmake, python, libcxxabi, fixDarwinDylibNames, version }:
+
+stdenv.mkDerivation rec {
+  name = "libc++-${version}";
+
+  src = fetch "libcxx" "1wdrxg365ig0kngx52pd0n820sncp24blb0zpalc579iidhh4002";
+
+  postUnpack = ''
+    unpackFile ${libcxxabi.src}
+    export LIBCXXABI_INCLUDE_DIR="$PWD/$(ls -d libcxxabi-${version}*)/include"
+  '';
+
+  patches = stdenv.lib.optional stdenv.hostPlatform.isMusl ../../libcxx-0001-musl-hacks.patch;
+
+  prePatch = ''
+    substituteInPlace lib/CMakeLists.txt --replace "/usr/lib/libc++" "\''${LIBCXX_LIBCXXABI_LIB_PATH}/libc++"
+  '';
+
+  preConfigure = ''
+    # Get headers from the cxxabi source so we can see private headers not installed by the cxxabi package
+    cmakeFlagsArray=($cmakeFlagsArray -DLIBCXX_CXX_ABI_INCLUDE_PATHS="$LIBCXXABI_INCLUDE_DIR")
+  '' + lib.optionalString stdenv.hostPlatform.isMusl ''
+    patchShebangs utils/cat_files.py
+  '';
+  nativeBuildInputs = [ cmake ] ++ stdenv.lib.optional stdenv.hostPlatform.isMusl python;
+
+  buildInputs = [ libcxxabi ] ++ lib.optional stdenv.isDarwin fixDarwinDylibNames;
+
+  cmakeFlags = [
+    "-DLIBCXX_LIBCXXABI_LIB_PATH=${libcxxabi}/lib"
+    "-DLIBCXX_LIBCPPABI_VERSION=2"
+    "-DLIBCXX_CXX_ABI=libcxxabi"
+  ] ++ stdenv.lib.optional stdenv.hostPlatform.isMusl "-DLIBCXX_HAS_MUSL_LIBC=1";
+
+  enableParallelBuilding = true;
+
+  linkCxxAbi = stdenv.isLinux;
+
+  setupHooks = [
+    ../../../../../build-support/setup-hooks/role.bash
+    ./setup-hook.sh
+  ];
+
+  meta = {
+    homepage = http://libcxx.llvm.org/;
+    description = "A new implementation of the C++ standard library, targeting C++11";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/libc++/setup-hook.sh b/nixpkgs/pkgs/development/compilers/llvm/7/libc++/setup-hook.sh
new file mode 100644
index 000000000000..6611259165ae
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/libc++/setup-hook.sh
@@ -0,0 +1,6 @@
+# See pkgs/build-support/setup-hooks/role.bash
+getHostRole
+
+linkCxxAbi="@linkCxxAbi@"
+export NIX_${role_pre}CXXSTDLIB_COMPILE+=" -isystem @out@/include/c++/v1"
+export NIX_${role_pre}CXXSTDLIB_LINK=" -stdlib=libc++${linkCxxAbi:+" -lc++abi"}"
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/libc++abi.nix b/nixpkgs/pkgs/development/compilers/llvm/7/libc++abi.nix
new file mode 100644
index 000000000000..b65b75b36886
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/libc++abi.nix
@@ -0,0 +1,50 @@
+{ stdenv, cmake, fetch, libcxx, libunwind, llvm, version }:
+
+stdenv.mkDerivation {
+  name = "libc++abi-${version}";
+
+  src = fetch "libcxxabi" "1n6yx0949l9bprh75dffchahn8wplkm79ffk4f2ap9vw2lx90s41";
+
+  nativeBuildInputs = [ cmake ];
+  buildInputs = stdenv.lib.optional (!stdenv.isDarwin && !stdenv.isFreeBSD) libunwind;
+
+  postUnpack = ''
+    unpackFile ${libcxx.src}
+    unpackFile ${llvm.src}
+    export cmakeFlags="-DLLVM_PATH=$PWD/$(ls -d llvm-*) -DLIBCXXABI_LIBCXX_PATH=$PWD/$(ls -d libcxx-*)"
+  '' + stdenv.lib.optionalString stdenv.isDarwin ''
+    export TRIPLE=x86_64-apple-darwin
+  '' + stdenv.lib.optionalString stdenv.hostPlatform.isMusl ''
+    patch -p1 -d $(ls -d libcxx-*) -i ${../libcxx-0001-musl-hacks.patch}
+  '';
+
+  installPhase = if stdenv.isDarwin
+    then ''
+      for file in lib/*.dylib; do
+        # this should be done in CMake, but having trouble figuring out
+        # the magic combination of necessary CMake variables
+        # if you fancy a try, take a look at
+        # http://www.cmake.org/Wiki/CMake_RPATH_handling
+        install_name_tool -id $out/$file $file
+      done
+      make install
+      install -d 755 $out/include
+      install -m 644 ../include/*.h $out/include
+    ''
+    else ''
+      install -d -m 755 $out/include $out/lib
+      install -m 644 lib/libc++abi.a $out/lib
+      install -m 644 lib/libc++abi.so.1.0 $out/lib
+      install -m 644 ../include/cxxabi.h $out/include
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so.1
+    '';
+
+  meta = {
+    homepage = http://libcxxabi.llvm.org/;
+    description = "A new implementation of low level support for a standard C++ library";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    maintainers = with stdenv.lib.maintainers; [ vlstill ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/lld.nix b/nixpkgs/pkgs/development/compilers/llvm/7/lld.nix
new file mode 100644
index 000000000000..33085eb3c808
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/lld.nix
@@ -0,0 +1,32 @@
+{ stdenv
+, fetch
+, cmake
+, libxml2
+, llvm
+, version
+}:
+
+stdenv.mkDerivation {
+  name = "lld-${version}";
+
+  src = fetch "lld" "0ca0qygrk87lhjk6cpv1wbmdfnficqqjsda3k7b013idvnralsc8";
+
+  nativeBuildInputs = [ cmake ];
+  buildInputs = [ llvm libxml2 ];
+
+  outputs = [ "out" "dev" ];
+
+  enableParallelBuilding = true;
+
+  postInstall = ''
+    moveToOutput include "$dev"
+    moveToOutput lib "$dev"
+  '';
+
+  meta = {
+    description = "The LLVM Linker";
+    homepage    = http://lld.llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/lldb.nix b/nixpkgs/pkgs/development/compilers/llvm/7/lldb.nix
new file mode 100644
index 000000000000..14cc0514fe6d
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/lldb.nix
@@ -0,0 +1,56 @@
+{ stdenv
+, fetch
+, cmake
+, zlib
+, ncurses
+, swig
+, which
+, libedit
+, libxml2
+, llvm
+, clang-unwrapped
+, python
+, version
+, darwin
+}:
+
+stdenv.mkDerivation {
+  name = "lldb-${version}";
+
+  src = fetch "lldb" "10k9lyk3i72j9hca523r9pz79qp7d8q7jqnjy0i3saj1bgknpd3n";
+
+  postPatch = ''
+    # Fix up various paths that assume llvm and clang are installed in the same place
+    sed -i 's,".*ClangConfig.cmake","${clang-unwrapped}/lib/cmake/clang/ClangConfig.cmake",' \
+      cmake/modules/LLDBStandalone.cmake
+    sed -i 's,".*tools/clang/include","${clang-unwrapped}/include",' \
+      cmake/modules/LLDBStandalone.cmake
+    sed -i 's,"$.LLVM_LIBRARY_DIR.",${llvm}/lib ${clang-unwrapped}/lib,' \
+      cmake/modules/LLDBStandalone.cmake
+  '';
+
+  nativeBuildInputs = [ cmake python which swig ];
+  buildInputs = [ ncurses zlib libedit libxml2 llvm ]
+    ++ stdenv.lib.optionals stdenv.isDarwin [ darwin.libobjc darwin.apple_sdk.libs.xpc darwin.apple_sdk.frameworks.Foundation darwin.bootstrap_cmds darwin.apple_sdk.frameworks.Carbon darwin.apple_sdk.frameworks.Cocoa darwin.cf-private ];
+
+  CXXFLAGS = "-fno-rtti";
+  hardeningDisable = [ "format" ];
+
+  cmakeFlags = [
+    "-DLLDB_CODESIGN_IDENTITY=" # codesigning makes nondeterministic
+  ];
+
+  enableParallelBuilding = true;
+
+  postInstall = ''
+    mkdir -p $out/share/man/man1
+    cp ../docs/lldb.1 $out/share/man/man1/
+  '';
+
+  meta = with stdenv.lib; {
+    description = "A next-generation high-performance debugger";
+    homepage    = http://llvm.org/;
+    license     = licenses.ncsa;
+    platforms   = platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/llvm-outputs.patch b/nixpkgs/pkgs/development/compilers/llvm/7/llvm-outputs.patch
new file mode 100644
index 000000000000..40096fa3497f
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/llvm-outputs.patch
@@ -0,0 +1,26 @@
+diff --git a/tools/llvm-config/llvm-config.cpp b/tools/llvm-config/llvm-config.cpp
+index 94d426b..37f7794 100644
+--- a/tools/llvm-config/llvm-config.cpp
++++ b/tools/llvm-config/llvm-config.cpp
+@@ -333,6 +333,21 @@ int main(int argc, char **argv) {
+     ActiveIncludeOption = "-I" + ActiveIncludeDir;
+   }
+ 
++  /// Nix-specific multiple-output handling: override ActiveLibDir if --link-shared
++  if (!IsInDevelopmentTree) {
++    bool WantShared = true;
++    for (int i = 1; i < argc; ++i) {
++      StringRef Arg = argv[i];
++      if (Arg == "--link-shared")
++        WantShared = true;
++      else if (Arg == "--link-static")
++        WantShared = false; // the last one wins
++    }
++
++    if (WantShared)
++      ActiveLibDir = std::string("@lib@") + "/lib" + LLVM_LIBDIR_SUFFIX;
++  }
++
+   /// We only use `shared library` mode in cases where the static library form
+   /// of the components provided are not available; note however that this is
+   /// skipped if we're run from within the build dir. However, once installed,
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/llvm.nix b/nixpkgs/pkgs/development/compilers/llvm/7/llvm.nix
new file mode 100644
index 000000000000..34f8a5478d1b
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/llvm.nix
@@ -0,0 +1,191 @@
+{ stdenv
+, fetch
+, fetchpatch
+, cmake
+, python
+, libffi
+, libbfd
+, libpfm
+, libxml2
+, ncurses
+, version
+, release_version
+, zlib
+, buildPackages
+, debugVersion ? false
+, enableManpages ? false
+, enableSharedLibraries ? true
+, enablePFM ? !stdenv.isDarwin
+, enablePolly ? false
+}:
+
+let
+  inherit (stdenv.lib) optional optionals optionalString;
+
+  src = fetch "llvm" "16s196wqzdw4pmri15hadzqgdi926zln3an2viwyq0kini6zr3d3";
+  polly_src = fetch "polly" "0wgvayfilgb530bq51l7szxfb13l24nnrmyji2f6ncq95a24dw8v";
+
+  # Used when creating a version-suffixed symlink of libLLVM.dylib
+  shortVersion = with stdenv.lib;
+    concatStringsSep "." (take 1 (splitString "." release_version));
+
+in stdenv.mkDerivation (rec {
+  name = "llvm-${version}";
+
+  unpackPhase = ''
+    unpackFile ${src}
+    mv llvm-${version}* llvm
+    sourceRoot=$PWD/llvm
+  '' + optionalString enablePolly ''
+    unpackFile ${polly_src}
+    mv polly-* $sourceRoot/tools/polly
+  '';
+
+  outputs = [ "out" "python" ]
+    ++ optional enableSharedLibraries "lib";
+
+  nativeBuildInputs = [ cmake python ]
+    ++ optional enableManpages python.pkgs.sphinx;
+
+  buildInputs = [ libxml2 libffi ]
+    ++ optional enablePFM libpfm; # exegesis
+
+  propagatedBuildInputs = [ ncurses zlib ];
+
+  patches = [
+    # https://bugs.llvm.org/show_bug.cgi?id=39427
+    # https://github.com/NixOS/nixpkgs/issues/54370
+    (fetchpatch {
+      url = "https://github.com/llvm-mirror/llvm/commit/57567def148f387153a8149fb590bd39b1b006a1.patch";
+      sha256 = "1w1xg5pxpc6cals1nf5j5k4p6qi8lcrpvn0paxc86m415i79xmcg";
+    })
+    # backport, fix building rust crates with lto
+    (fetchpatch {
+      url = "https://github.com/llvm-mirror/llvm/commit/da1fb72bb305d6bc1f3899d541414146934bf80f.patch";
+      sha256 = "0p81gkhc1xhcx0hmnkwyhrn8x8l8fd24xgaj1whni29yga466dwc";
+    })
+    (fetchpatch {
+      url = "https://github.com/llvm-mirror/llvm/commit/cc1f2a595ead516812a6c50398f0f3480ebe031f.patch";
+      sha256 = "0k6k1p5yisgwx417a67s7sr9930rqh1n0zv5jvply8vjjy4b3kf8";
+    })
+  ];
+
+  postPatch = optionalString stdenv.isDarwin ''
+    substituteInPlace cmake/modules/AddLLVM.cmake \
+      --replace 'set(_install_name_dir INSTALL_NAME_DIR "@rpath")' "set(_install_name_dir)" \
+      --replace 'set(_install_rpath "@loader_path/../lib" ''${extra_libdir})' ""
+  ''
+  # Patch llvm-config to return correct library path based on --link-{shared,static}.
+  + optionalString (enableSharedLibraries) ''
+    substitute '${./llvm-outputs.patch}' ./llvm-outputs.patch --subst-var lib
+    patch -p1 < ./llvm-outputs.patch
+  '' + ''
+    # FileSystem permissions tests fail with various special bits
+    substituteInPlace unittests/Support/CMakeLists.txt \
+      --replace "Path.cpp" ""
+    rm unittests/Support/Path.cpp
+  '' + optionalString stdenv.hostPlatform.isMusl ''
+    patch -p1 -i ${../TLI-musl.patch}
+    substituteInPlace unittests/Support/CMakeLists.txt \
+      --replace "add_subdirectory(DynamicLibrary)" ""
+    rm unittests/Support/DynamicLibrary/DynamicLibraryTest.cpp
+  '' + ''
+    patchShebangs test/BugPoint/compile-custom.ll.py
+  '';
+
+  # hacky fix: created binaries need to be run before installation
+  preBuild = ''
+    mkdir -p $out/
+    ln -sv $PWD/lib $out
+  '';
+
+  cmakeFlags = with stdenv; [
+    "-DCMAKE_BUILD_TYPE=${if debugVersion then "Debug" else "Release"}"
+    "-DLLVM_INSTALL_UTILS=ON"  # Needed by rustc
+    "-DLLVM_BUILD_TESTS=ON"
+    "-DLLVM_ENABLE_FFI=ON"
+    "-DLLVM_ENABLE_RTTI=ON"
+    "-DLLVM_HOST_TRIPLE=${stdenv.hostPlatform.config}"
+    "-DLLVM_DEFAULT_TARGET_TRIPLE=${stdenv.hostPlatform.config}"
+    "-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=WebAssembly"
+    "-DLLVM_ENABLE_DUMP=ON"
+  ] ++ optionals enableSharedLibraries [
+    "-DLLVM_LINK_LLVM_DYLIB=ON"
+  ] ++ optionals enableManpages [
+    "-DLLVM_BUILD_DOCS=ON"
+    "-DLLVM_ENABLE_SPHINX=ON"
+    "-DSPHINX_OUTPUT_MAN=ON"
+    "-DSPHINX_OUTPUT_HTML=OFF"
+    "-DSPHINX_WARNINGS_AS_ERRORS=OFF"
+  ] ++ optionals (!isDarwin) [
+    "-DLLVM_BINUTILS_INCDIR=${libbfd.dev}/include"
+  ] ++ optionals (isDarwin) [
+    "-DLLVM_ENABLE_LIBCXX=ON"
+    "-DCAN_TARGET_i386=false"
+  ] ++ optionals (stdenv.hostPlatform != stdenv.buildPlatform) [
+    "-DCMAKE_CROSSCOMPILING=True"
+    "-DLLVM_TABLEGEN=${buildPackages.llvm_7}/bin/llvm-tblgen"
+  ];
+
+  postBuild = ''
+    rm -fR $out
+  '';
+
+  preCheck = ''
+    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PWD/lib
+  '';
+
+  postInstall = ''
+    mkdir -p $python/share
+    mv $out/share/opt-viewer $python/share/opt-viewer
+  ''
+  + optionalString enableSharedLibraries ''
+    moveToOutput "lib/libLLVM-*" "$lib"
+    moveToOutput "lib/libLLVM${stdenv.hostPlatform.extensions.sharedLibrary}" "$lib"
+    substituteInPlace "$out/lib/cmake/llvm/LLVMExports-${if debugVersion then "debug" else "release"}.cmake" \
+      --replace "\''${_IMPORT_PREFIX}/lib/libLLVM-" "$lib/lib/libLLVM-"
+  ''
+  + optionalString (stdenv.isDarwin && enableSharedLibraries) ''
+    substituteInPlace "$out/lib/cmake/llvm/LLVMExports-${if debugVersion then "debug" else "release"}.cmake" \
+      --replace "\''${_IMPORT_PREFIX}/lib/libLLVM.dylib" "$lib/lib/libLLVM.dylib"
+    ln -s $lib/lib/libLLVM.dylib $lib/lib/libLLVM-${shortVersion}.dylib
+    ln -s $lib/lib/libLLVM.dylib $lib/lib/libLLVM-${release_version}.dylib
+  '';
+
+  doCheck = stdenv.isLinux && (!stdenv.isx86_32);
+
+  checkTarget = "check-all";
+
+  enableParallelBuilding = true;
+
+  passthru.src = src;
+
+  meta = {
+    description = "Collection of modular and reusable compiler and toolchain technologies";
+    homepage    = http://llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    maintainers = with stdenv.lib.maintainers; [ lovek323 raskin dtzWill ];
+    platforms   = stdenv.lib.platforms.all;
+  };
+} // stdenv.lib.optionalAttrs enableManpages {
+  name = "llvm-manpages-${version}";
+
+  buildPhase = ''
+    make docs-llvm-man
+  '';
+
+  propagatedBuildInputs = [];
+
+  installPhase = ''
+    make -C docs install
+  '';
+
+  postPatch = null;
+  postInstall = null;
+
+  outputs = [ "out" ];
+
+  doCheck = false;
+
+  meta.description = "man pages for LLVM ${version}";
+})
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/openmp.nix b/nixpkgs/pkgs/development/compilers/llvm/7/openmp.nix
new file mode 100644
index 000000000000..fb856eaa51fd
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/openmp.nix
@@ -0,0 +1,25 @@
+{ stdenv
+, fetch
+, cmake
+, llvm
+, perl
+, version
+}:
+
+stdenv.mkDerivation {
+  name = "openmp-${version}";
+
+  src = fetch "openmp" "030dkg5cypd7j9hq0mcqb5gs31lxwmzfq52j81l7v9ldcy5bf5mz";
+
+  nativeBuildInputs = [ cmake perl ];
+  buildInputs = [ llvm ];
+
+  enableParallelBuilding = true;
+
+  meta = {
+    description = "Components required to build an executable OpenMP program";
+    homepage    = http://openmp.llvm.org/;
+    license     = stdenv.lib.licenses.mit;
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/7/sanitizers-nongnu.patch b/nixpkgs/pkgs/development/compilers/llvm/7/sanitizers-nongnu.patch
new file mode 100644
index 000000000000..1f2ac97818eb
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/7/sanitizers-nongnu.patch
@@ -0,0 +1,412 @@
+From f7a253f8f85d0f49df6b73996737a3e84ac64236 Mon Sep 17 00:00:00 2001
+From: Will Dietz <w@wdtz.org>
+Date: Mon, 24 Sep 2018 11:17:25 -0500
+Subject: [PATCH] Ported to 7.0, taken from gentoo-musl project.
+
+------
+Ported to compiler-rt-sanitizers-5.0.0. Taken from
+
+https://gist.githubusercontent.com/pwaller/2337f3290f12634cad3e3730cff0a6c1/raw/83c87a8585e2f9662494db5662e5361beb093c26/nongnu.patch
+Signed-off-by: Jory A. Pratt <anarchy@gentoo.org>
+
+Taken from gentoo-musl project, with a few additional minor fixes.
+---
+ lib/asan/asan_linux.cc                        |  4 +-
+ lib/interception/interception_linux.cc        |  2 +-
+ lib/interception/interception_linux.h         |  2 +-
+ lib/msan/msan_linux.cc                        |  2 +-
+ lib/sanitizer_common/sanitizer_allocator.cc   |  2 +-
+ .../sanitizer_common_interceptors_ioctl.inc   |  4 +-
+ .../sanitizer_common_syscalls.inc             |  2 +-
+ lib/sanitizer_common/sanitizer_linux.cc       |  8 +++-
+ .../sanitizer_linux_libcdep.cc                | 10 ++---
+ lib/sanitizer_common/sanitizer_platform.h     |  6 +++
+ .../sanitizer_platform_interceptors.h         |  4 +-
+ .../sanitizer_platform_limits_posix.cc        | 37 +++++++++++--------
+ lib/tsan/rtl/tsan_platform_linux.cc           |  2 +-
+ 13 files changed, 51 insertions(+), 34 deletions(-)
+
+diff --git a/lib/asan/asan_linux.cc b/lib/asan/asan_linux.cc
+index 625f32d40..73cf77aca 100644
+--- a/lib/asan/asan_linux.cc
++++ b/lib/asan/asan_linux.cc
+@@ -46,7 +46,7 @@
+ #include <link.h>
+ #endif
+ 
+-#if SANITIZER_ANDROID || SANITIZER_FREEBSD || SANITIZER_SOLARIS
++#if SANITIZER_ANDROID || SANITIZER_FREEBSD || SANITIZER_SOLARIS || SANITIZER_NONGNU
+ #include <ucontext.h>
+ extern "C" void* _DYNAMIC;
+ #elif SANITIZER_NETBSD
+@@ -139,7 +139,7 @@ void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
+   UNIMPLEMENTED();
+ }
+ 
+-#if SANITIZER_ANDROID
++#if SANITIZER_ANDROID || SANITIZER_NONGNU
+ // FIXME: should we do anything for Android?
+ void AsanCheckDynamicRTPrereqs() {}
+ void AsanCheckIncompatibleRT() {}
+diff --git a/lib/interception/interception_linux.cc b/lib/interception/interception_linux.cc
+index 26bfcd8f6..529b234f7 100644
+--- a/lib/interception/interception_linux.cc
++++ b/lib/interception/interception_linux.cc
+@@ -43,7 +43,7 @@ bool GetRealFunctionAddress(const char *func_name, uptr *func_addr,
+ }
+ 
+ // Android and Solaris do not have dlvsym
+-#if !SANITIZER_ANDROID && !SANITIZER_SOLARIS && !SANITIZER_OPENBSD
++#if !SANITIZER_ANDROID && !SANITIZER_SOLARIS && !SANITIZER_OPENBSD && !SANITIZER_NONGNU
+ void *GetFuncAddrVer(const char *func_name, const char *ver) {
+   return dlvsym(RTLD_NEXT, func_name, ver);
+ }
+diff --git a/lib/interception/interception_linux.h b/lib/interception/interception_linux.h
+index 942c25609..24a4d5080 100644
+--- a/lib/interception/interception_linux.h
++++ b/lib/interception/interception_linux.h
+@@ -36,7 +36,7 @@ void *GetFuncAddrVer(const char *func_name, const char *ver);
+       (::__interception::uptr) & WRAP(func))
+ 
+ // Android,  Solaris and OpenBSD do not have dlvsym
+-#if !SANITIZER_ANDROID && !SANITIZER_SOLARIS && !SANITIZER_OPENBSD
++#if !SANITIZER_ANDROID && !SANITIZER_SOLARIS && !SANITIZER_OPENBSD && !SANITIZER_NONGNU
+ #define INTERCEPT_FUNCTION_VER_LINUX_OR_FREEBSD(func, symver) \
+   (::__interception::real_##func = (func##_f)(                \
+        unsigned long)::__interception::GetFuncAddrVer(#func, symver))
+diff --git a/lib/msan/msan_linux.cc b/lib/msan/msan_linux.cc
+index 385a650c4..6e30a8ce9 100644
+--- a/lib/msan/msan_linux.cc
++++ b/lib/msan/msan_linux.cc
+@@ -13,7 +13,7 @@
+ //===----------------------------------------------------------------------===//
+ 
+ #include "sanitizer_common/sanitizer_platform.h"
+-#if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD
++#if SANITIZER_FREEBSD || (SANITIZER_LINUX && !SANITIZER_NONGNU) || SANITIZER_NETBSD
+ 
+ #include "msan.h"
+ #include "msan_report.h"
+diff --git a/lib/sanitizer_common/sanitizer_allocator.cc b/lib/sanitizer_common/sanitizer_allocator.cc
+index 6bfd5e5ee..048f6154f 100644
+--- a/lib/sanitizer_common/sanitizer_allocator.cc
++++ b/lib/sanitizer_common/sanitizer_allocator.cc
+@@ -27,7 +27,7 @@ const char *SecondaryAllocatorName = "LargeMmapAllocator";
+ 
+ // ThreadSanitizer for Go uses libc malloc/free.
+ #if SANITIZER_GO || defined(SANITIZER_USE_MALLOC)
+-# if SANITIZER_LINUX && !SANITIZER_ANDROID
++# if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ extern "C" void *__libc_malloc(uptr size);
+ #  if !SANITIZER_GO
+ extern "C" void *__libc_memalign(uptr alignment, uptr size);
+diff --git a/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc b/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
+index 2d633c173..b6eb23116 100644
+--- a/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
++++ b/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
+@@ -104,7 +104,7 @@ static void ioctl_table_fill() {
+   _(SIOCGETVIFCNT, WRITE, struct_sioc_vif_req_sz);
+ #endif
+ 
+-#if SANITIZER_LINUX
++#if SANITIZER_LINUX && !SANITIZER_NONGNU
+   // Conflicting request ids.
+   // _(CDROMAUDIOBUFSIZ, NONE, 0);
+   // _(SNDCTL_TMR_CONTINUE, NONE, 0);
+@@ -365,7 +365,7 @@ static void ioctl_table_fill() {
+   _(VT_WAITACTIVE, NONE, 0);
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   // _(SIOCDEVPLIP, WRITE, struct_ifreq_sz); // the same as EQL_ENSLAVE
+   _(CYGETDEFTHRESH, WRITE, sizeof(int));
+   _(CYGETDEFTIMEOUT, WRITE, sizeof(int));
+diff --git a/lib/sanitizer_common/sanitizer_common_syscalls.inc b/lib/sanitizer_common/sanitizer_common_syscalls.inc
+index 469c8eb7e..24f87867d 100644
+--- a/lib/sanitizer_common/sanitizer_common_syscalls.inc
++++ b/lib/sanitizer_common/sanitizer_common_syscalls.inc
+@@ -2038,7 +2038,7 @@ POST_SYSCALL(setrlimit)(long res, long resource, void *rlim) {
+   }
+ }
+ 
+-#if !SANITIZER_ANDROID
++#if !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ PRE_SYSCALL(prlimit64)(long pid, long resource, const void *new_rlim,
+                        void *old_rlim) {
+   if (new_rlim) PRE_READ(new_rlim, struct_rlimit64_sz);
+diff --git a/lib/sanitizer_common/sanitizer_linux.cc b/lib/sanitizer_common/sanitizer_linux.cc
+index 96d6c1eff..9e2b7fb9d 100644
+--- a/lib/sanitizer_common/sanitizer_linux.cc
++++ b/lib/sanitizer_common/sanitizer_linux.cc
+@@ -541,13 +541,13 @@ const char *GetEnv(const char *name) {
+ #endif
+ }
+ 
+-#if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_OPENBSD
++#if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_OPENBSD && !SANITIZER_NONGNU
+ extern "C" {
+ SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
+ }
+ #endif
+ 
+-#if !SANITIZER_GO && !SANITIZER_FREEBSD && !SANITIZER_NETBSD &&                \
++#if (!SANITIZER_GO || SANITIZER_NONGNU) && !SANITIZER_FREEBSD && !SANITIZER_NETBSD &&                \
+     !SANITIZER_OPENBSD
+ static void ReadNullSepFileToArray(const char *path, char ***arr,
+                                    int arr_size) {
+@@ -590,6 +590,10 @@ static void GetArgsAndEnv(char ***argv, char ***envp) {
+ #elif SANITIZER_NETBSD
+   *argv = __ps_strings->ps_argvstr;
+   *envp = __ps_strings->ps_envstr;
++#elif SANITIZER_NONGNU
++    static const int kMaxArgv = 2000, kMaxEnvp = 2000;
++    ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
++    ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
+ #else // SANITIZER_FREEBSD
+ #if !SANITIZER_GO
+   if (&__libc_stack_end) {
+diff --git a/lib/sanitizer_common/sanitizer_linux_libcdep.cc b/lib/sanitizer_common/sanitizer_linux_libcdep.cc
+index 4962ff832..438f94dbe 100644
+--- a/lib/sanitizer_common/sanitizer_linux_libcdep.cc
++++ b/lib/sanitizer_common/sanitizer_linux_libcdep.cc
+@@ -179,7 +179,7 @@ __attribute__((unused)) static bool GetLibcVersion(int *major, int *minor,
+ }
+ 
+ #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO &&               \
+-    !SANITIZER_NETBSD && !SANITIZER_OPENBSD && !SANITIZER_SOLARIS
++    !SANITIZER_NETBSD && !SANITIZER_OPENBSD && !SANITIZER_SOLARIS && !SANITIZER_NONGNU
+ static uptr g_tls_size;
+ 
+ #ifdef __i386__
+@@ -261,7 +261,7 @@ void InitTlsSize() { }
+ #if (defined(__x86_64__) || defined(__i386__) || defined(__mips__) ||          \
+      defined(__aarch64__) || defined(__powerpc64__) || defined(__s390__) ||    \
+      defined(__arm__)) &&                                                      \
+-    SANITIZER_LINUX && !SANITIZER_ANDROID
++    SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ // sizeof(struct pthread) from glibc.
+ static atomic_uintptr_t thread_descriptor_size;
+ 
+@@ -426,7 +426,7 @@ int GetSizeFromHdr(struct dl_phdr_info *info, size_t size, void *data) {
+ 
+ #if !SANITIZER_GO
+ static void GetTls(uptr *addr, uptr *size) {
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ # if defined(__x86_64__) || defined(__i386__) || defined(__s390__)
+   *addr = ThreadSelf();
+   *size = GetTlsSize();
+@@ -470,7 +470,7 @@ static void GetTls(uptr *addr, uptr *size) {
+ #elif SANITIZER_OPENBSD
+   *addr = 0;
+   *size = 0;
+-#elif SANITIZER_ANDROID
++#elif SANITIZER_ANDROID || SANITIZER_NONGNU
+   *addr = 0;
+   *size = 0;
+ #elif SANITIZER_SOLARIS
+@@ -486,7 +486,7 @@ static void GetTls(uptr *addr, uptr *size) {
+ #if !SANITIZER_GO
+ uptr GetTlsSize() {
+ #if SANITIZER_FREEBSD || SANITIZER_ANDROID || SANITIZER_NETBSD ||              \
+-    SANITIZER_OPENBSD || SANITIZER_SOLARIS
++    SANITIZER_OPENBSD || SANITIZER_SOLARIS || SANITIZER_NONGNU
+   uptr addr, size;
+   GetTls(&addr, &size);
+   return size;
+diff --git a/lib/sanitizer_common/sanitizer_platform.h b/lib/sanitizer_common/sanitizer_platform.h
+index d81e25580..e10680ac8 100644
+--- a/lib/sanitizer_common/sanitizer_platform.h
++++ b/lib/sanitizer_common/sanitizer_platform.h
+@@ -208,6 +208,12 @@
+ # define SANITIZER_SOLARIS32 0
+ #endif
+ 
++#if defined(__linux__) && !defined(__GLIBC__)
++# define SANITIZER_NONGNU 1
++#else
++# define SANITIZER_NONGNU 0
++#endif
++
+ #if defined(__myriad2__)
+ # define SANITIZER_MYRIAD2 1
+ #else
+diff --git a/lib/sanitizer_common/sanitizer_platform_interceptors.h b/lib/sanitizer_common/sanitizer_platform_interceptors.h
+index f95539a73..6c53b3415 100644
+--- a/lib/sanitizer_common/sanitizer_platform_interceptors.h
++++ b/lib/sanitizer_common/sanitizer_platform_interceptors.h
+@@ -39,7 +39,7 @@
+ # include "sanitizer_platform_limits_solaris.h"
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ # define SI_LINUX_NOT_ANDROID 1
+ #else
+ # define SI_LINUX_NOT_ANDROID 0
+@@ -322,7 +322,7 @@
+ #define SANITIZER_INTERCEPT_ETHER_R (SI_FREEBSD || SI_LINUX_NOT_ANDROID)
+ #define SANITIZER_INTERCEPT_SHMCTL          \
+   (SI_NETBSD || SI_OPENBSD || SI_SOLARIS || \
+-  ((SI_FREEBSD || SI_LINUX_NOT_ANDROID) && \
++  ((SI_FREEBSD || SI_LINUX_NOT_ANDROID || SANITIZER_NONGNU) && \
+     SANITIZER_WORDSIZE == 64))  // NOLINT
+ #define SANITIZER_INTERCEPT_RANDOM_R SI_LINUX_NOT_ANDROID
+ #define SANITIZER_INTERCEPT_PTHREAD_ATTR_GET SI_POSIX
+diff --git a/lib/sanitizer_common/sanitizer_platform_limits_posix.cc b/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
+index 54da635d7..2f6ff69c3 100644
+--- a/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
++++ b/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
+@@ -14,6 +14,9 @@
+ 
+ #include "sanitizer_platform.h"
+ 
++// Workaround musl <--> linux conflicting definition of 'struct sysinfo'
++#define _LINUX_SYSINFO_H
++
+ #if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_MAC
+ // Tests in this file assume that off_t-dependent data structures match the
+ // libc ABI. For example, struct dirent here is what readdir() function (as
+@@ -138,12 +141,14 @@ typedef struct user_fpregs elf_fpregset_t;
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+ #include <glob.h>
+-#include <obstack.h>
++#  if !SANITIZER_NONGNU
++#    include <obstack.h>
++#  endif
+ #include <mqueue.h>
+-#include <net/if_ppp.h>
+-#include <netax25/ax25.h>
+-#include <netipx/ipx.h>
+-#include <netrom/netrom.h>
++#include <linux/if_ppp.h>
++#include <linux/ax25.h>
++#include <linux/ipx.h>
++#include <linux/netrom.h>
+ #if HAVE_RPC_XDR_H
+ # include <rpc/xdr.h>
+ #elif HAVE_TIRPC_RPC_XDR_H
+@@ -251,7 +256,7 @@ namespace __sanitizer {
+   unsigned struct_itimerspec_sz = sizeof(struct itimerspec);
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   // Use pre-computed size of struct ustat to avoid <sys/ustat.h> which
+   // has been removed from glibc 2.28.
+ #if defined(__aarch64__) || defined(__s390x__) || defined (__mips64) \
+@@ -322,7 +327,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(ElfW(Phdr));
+ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+ #endif
+ 
+-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
++#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   int glob_nomatch = GLOB_NOMATCH;
+   int glob_altdirfunc = GLOB_ALTDIRFUNC;
+ #endif
+@@ -416,7 +421,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned struct_termios_sz = sizeof(struct termios);
+   unsigned struct_winsize_sz = sizeof(struct winsize);
+ 
+-#if SANITIZER_LINUX
++#if SANITIZER_LINUX && !SANITIZER_NONGNU
+   unsigned struct_arpreq_sz = sizeof(struct arpreq);
+   unsigned struct_cdrom_msf_sz = sizeof(struct cdrom_msf);
+   unsigned struct_cdrom_multisession_sz = sizeof(struct cdrom_multisession);
+@@ -466,7 +471,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned struct_vt_mode_sz = sizeof(struct vt_mode);
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   unsigned struct_ax25_parms_struct_sz = sizeof(struct ax25_parms_struct);
+   unsigned struct_cyclades_monitor_sz = sizeof(struct cyclades_monitor);
+ #if EV_VERSION > (0x010000)
+@@ -834,7 +839,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned IOCTL_VT_WAITACTIVE = VT_WAITACTIVE;
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   unsigned IOCTL_CYGETDEFTHRESH = CYGETDEFTHRESH;
+   unsigned IOCTL_CYGETDEFTIMEOUT = CYGETDEFTIMEOUT;
+   unsigned IOCTL_CYGETMON = CYGETMON;
+@@ -989,7 +994,7 @@ CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phdr);
+ CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phnum);
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
++#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ CHECK_TYPE_SIZE(glob_t);
+ CHECK_SIZE_AND_OFFSET(glob_t, gl_pathc);
+ CHECK_SIZE_AND_OFFSET(glob_t, gl_pathv);
+@@ -1023,6 +1028,7 @@ CHECK_TYPE_SIZE(iovec);
+ CHECK_SIZE_AND_OFFSET(iovec, iov_base);
+ CHECK_SIZE_AND_OFFSET(iovec, iov_len);
+ 
++#if !SANITIZER_NONGNU
+ CHECK_TYPE_SIZE(msghdr);
+ CHECK_SIZE_AND_OFFSET(msghdr, msg_name);
+ CHECK_SIZE_AND_OFFSET(msghdr, msg_namelen);
+@@ -1036,6 +1042,7 @@ CHECK_TYPE_SIZE(cmsghdr);
+ CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_len);
+ CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_level);
+ CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_type);
++#endif
+ 
+ #ifndef __GLIBC_PREREQ
+ #define __GLIBC_PREREQ(x, y) 0
+@@ -1145,7 +1152,7 @@ CHECK_SIZE_AND_OFFSET(mntent, mnt_passno);
+ 
+ CHECK_TYPE_SIZE(ether_addr);
+ 
+-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
++#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ CHECK_TYPE_SIZE(ipc_perm);
+ # if SANITIZER_FREEBSD
+ CHECK_SIZE_AND_OFFSET(ipc_perm, key);
+@@ -1206,7 +1213,7 @@ CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_dstaddr);
+ CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_data);
+ #endif
+ 
+-#if SANITIZER_LINUX
++#if SANITIZER_LINUX && !SANITIZER_NONGNU
+ COMPILER_CHECK(sizeof(__sanitizer_mallinfo) == sizeof(struct mallinfo));
+ #endif
+ 
+@@ -1256,7 +1263,7 @@ COMPILER_CHECK(__sanitizer_XDR_DECODE == XDR_DECODE);
+ COMPILER_CHECK(__sanitizer_XDR_FREE == XDR_FREE);
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ COMPILER_CHECK(sizeof(__sanitizer_FILE) <= sizeof(FILE));
+ CHECK_SIZE_AND_OFFSET(FILE, _flags);
+ CHECK_SIZE_AND_OFFSET(FILE, _IO_read_ptr);
+@@ -1275,7 +1282,7 @@ CHECK_SIZE_AND_OFFSET(FILE, _chain);
+ CHECK_SIZE_AND_OFFSET(FILE, _fileno);
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ COMPILER_CHECK(sizeof(__sanitizer__obstack_chunk) <= sizeof(_obstack_chunk));
+ CHECK_SIZE_AND_OFFSET(_obstack_chunk, limit);
+ CHECK_SIZE_AND_OFFSET(_obstack_chunk, prev);
+diff --git a/lib/tsan/rtl/tsan_platform_linux.cc b/lib/tsan/rtl/tsan_platform_linux.cc
+index de989b780..51a97b554 100644
+--- a/lib/tsan/rtl/tsan_platform_linux.cc
++++ b/lib/tsan/rtl/tsan_platform_linux.cc
+@@ -294,7 +294,7 @@ void InitializePlatform() {
+ // This is required to properly "close" the fds, because we do not see internal
+ // closes within glibc. The code is a pure hack.
+ int ExtractResolvFDs(void *state, int *fds, int nfd) {
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   int cnt = 0;
+   struct __res_state *statp = (struct __res_state*)state;
+   for (int i = 0; i < MAXNS && cnt < nfd; i++) {
+-- 
+2.19.0
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/bintools.nix b/nixpkgs/pkgs/development/compilers/llvm/8/bintools.nix
new file mode 100644
index 000000000000..72a2a7331930
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/bintools.nix
@@ -0,0 +1,19 @@
+{ runCommand, stdenv, llvm, lld, version }:
+
+let
+  prefix =
+    if stdenv.hostPlatform != stdenv.targetPlatform
+    then "${stdenv.targetPlatform.config}-"
+    else "";
+in runCommand "llvm-binutils-${version}" { preferLocalBuild = true; } ''
+   mkdir -p $out/bin
+   for prog in ${lld}/bin/*; do
+     ln -s $prog $out/bin/${prefix}$(basename $prog)
+   done
+   for prog in ${llvm}/bin/*; do
+     ln -s $prog $out/bin/${prefix}$(echo $(basename $prog) | sed -e "s|llvm-||")
+     ln -sf $prog $out/bin/${prefix}$(basename $prog)
+   done
+   rm -f $out/bin/${prefix}cat
+   ln -s ${lld}/bin/lld $out/bin/${prefix}ld
+''
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/clang/clang-xpc.patch b/nixpkgs/pkgs/development/compilers/llvm/8/clang/clang-xpc.patch
new file mode 100644
index 000000000000..eb57d3458228
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/clang/clang-xpc.patch
@@ -0,0 +1,41 @@
+From 61c9b97d7b81cc2c013b423bf1763a92b14fcae3 Mon Sep 17 00:00:00 2001
+From: Jan Korous <jkorous@apple.com>
+Date: Tue, 26 Mar 2019 03:48:25 +0000
+Subject: [PATCH] [clangd][xpc][cmake] Respect explicit value of
+ CLANGD_BUILD_XPC
+
+We shouldn't prevent user from disabling XPC framework build on Darwin.
+However, by keeping it on by default our CI systems also test
+it by default on macOS.
+
+Based on user request:
+http://lists.llvm.org/pipermail/cfe-dev/2019-March/061778.html
+
+Differential Revision: https://reviews.llvm.org/D59808
+
+git-svn-id: https://llvm.org/svn/llvm-project/clang-tools-extra/trunk@356974 91177308-0d34-0410-b5e6-96231b3b80d8
+---
+ CMakeLists.txt | 13 ++++++++++---
+ 1 file changed, 10 insertions(+), 3 deletions(-)
+
+diff --git a/CMakeLists.txt b/CMakeLists.txt
+index 66ebeaeeaa..514b17fb3c 100644
+--- a/tools/extra/CMakeLists.txt
++++ b/tools/extra/CMakeLists.txt
+@@ -1,6 +1,13 @@
+-option(CLANGD_BUILD_XPC "Build XPC Support For Clangd." OFF)
+-if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
+-  set(CLANGD_BUILD_XPC ON CACHE BOOL "" FORCE)
++if (NOT DEFINED CLANGD_BUILD_XPC)
++  if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
++    set(CLANGD_BUILD_XPC_DEFAULT ON)
++  else ()
++    set(CLANGD_BUILD_XPC_DEFAULT OFF)
++  endif ()
++
++  set(CLANGD_BUILD_XPC ${CLANGD_BUILD_XPC_DEFAULT} CACHE BOOL "Build XPC Support For Clangd." FORCE)
++
++  unset(CLANGD_BUILD_XPC_DEFAULT)
+ endif ()
+ 
+ add_subdirectory(clang-apply-replacements)
\ No newline at end of file
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/clang/default.nix b/nixpkgs/pkgs/development/compilers/llvm/8/clang/default.nix
new file mode 100644
index 000000000000..8709e47dd3aa
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/clang/default.nix
@@ -0,0 +1,122 @@
+{ stdenv, fetch, fetchpatch, cmake, libxml2, llvm, version, clang-tools-extra_src, python
+, fixDarwinDylibNames
+, enableManpages ? false
+, enablePolly ? false # TODO: get this info from llvm (passthru?)
+}:
+
+let
+  self = stdenv.mkDerivation ({
+    name = "clang-${version}";
+
+    unpackPhase = ''
+      unpackFile ${fetch "cfe" "0svk1f70hvpwrjp6x5i9kqwrqwxnmcrw5s7f4cxyd100mdd12k08"}
+      mv cfe-${version}* clang
+      sourceRoot=$PWD/clang
+      unpackFile ${clang-tools-extra_src}
+      mv clang-tools-extra-* $sourceRoot/tools/extra
+    '';
+
+    nativeBuildInputs = [ cmake python ]
+      ++ stdenv.lib.optional enableManpages python.pkgs.sphinx;
+
+    buildInputs = [ libxml2 llvm ]
+      ++ stdenv.lib.optional stdenv.isDarwin fixDarwinDylibNames;
+
+    cmakeFlags = [
+      "-DCMAKE_CXX_FLAGS=-std=c++11"
+      "-DCLANGD_BUILD_XPC=OFF"
+    ] ++ stdenv.lib.optionals enableManpages [
+      "-DCLANG_INCLUDE_DOCS=ON"
+      "-DLLVM_ENABLE_SPHINX=ON"
+      "-DSPHINX_OUTPUT_MAN=ON"
+      "-DSPHINX_OUTPUT_HTML=OFF"
+      "-DSPHINX_WARNINGS_AS_ERRORS=OFF"
+    ] ++ stdenv.lib.optionals enablePolly [
+      "-DWITH_POLLY=ON"
+      "-DLINK_POLLY_INTO_TOOLS=ON"
+    ];
+
+    patches = [
+      ./purity.patch
+      ./clang-xpc.patch
+      # Backport for -static-pie, which the latter touches, and which is nice in
+      # its own right.
+      ./static-pie.patch
+      # Backport for the `--unwindlib=[libgcc|complier-rt]` flag, which is
+      # needed for our bootstrapping to not interfere with C.
+      ./unwindlib.patch
+    ];
+
+    postPatch = ''
+      sed -i -e 's/DriverArgs.hasArg(options::OPT_nostdlibinc)/true/' \
+             -e 's/Args.hasArg(options::OPT_nostdlibinc)/true/' \
+             lib/Driver/ToolChains/*.cpp
+
+      # Patch for standalone doc building
+      sed -i '1s,^,find_package(Sphinx REQUIRED)\n,' docs/CMakeLists.txt
+    '' + stdenv.lib.optionalString stdenv.hostPlatform.isMusl ''
+      sed -i -e 's/lgcc_s/lgcc_eh/' lib/Driver/ToolChains/*.cpp
+    '' + stdenv.lib.optionalString stdenv.hostPlatform.isDarwin ''
+      substituteInPlace tools/extra/clangd/CMakeLists.txt \
+        --replace "NOT HAVE_CXX_ATOMICS64_WITHOUT_LIB" FALSE
+    '';
+
+    outputs = [ "out" "lib" "python" ];
+
+    # Clang expects to find LLVMgold in its own prefix
+    postInstall = ''
+      if [ -e ${llvm}/lib/LLVMgold.so ]; then
+        ln -sv ${llvm}/lib/LLVMgold.so $out/lib
+      fi
+
+      ln -sv $out/bin/clang $out/bin/cpp
+
+      # Move libclang to 'lib' output
+      moveToOutput "lib/libclang.*" "$lib"
+      substituteInPlace $out/lib/cmake/clang/ClangTargets-release.cmake \
+          --replace "\''${_IMPORT_PREFIX}/lib/libclang." "$lib/lib/libclang."
+
+      mkdir -p $python/bin $python/share/clang/
+      mv $out/bin/{git-clang-format,scan-view} $python/bin
+      if [ -e $out/bin/set-xcode-analyzer ]; then
+        mv $out/bin/set-xcode-analyzer $python/bin
+      fi
+      mv $out/share/clang/*.py $python/share/clang
+      rm $out/bin/c-index-test
+    '';
+
+    enableParallelBuilding = true;
+
+    passthru = {
+      isClang = true;
+      inherit llvm;
+    } // stdenv.lib.optionalAttrs (stdenv.targetPlatform.isLinux || (stdenv.cc.isGNU && stdenv.cc.cc ? gcc)) {
+      gcc = if stdenv.cc.isGNU then stdenv.cc.cc else stdenv.cc.cc.gcc;
+    };
+
+    meta = {
+      description = "A c, c++, objective-c, and objective-c++ frontend for the llvm compiler";
+      homepage    = http://llvm.org/;
+      license     = stdenv.lib.licenses.ncsa;
+      platforms   = stdenv.lib.platforms.all;
+    };
+  } // stdenv.lib.optionalAttrs enableManpages {
+    name = "clang-manpages-${version}";
+
+    buildPhase = ''
+      make docs-clang-man
+    '';
+
+    installPhase = ''
+      mkdir -p $out/share/man/man1
+      # Manually install clang manpage
+      cp docs/man/*.1 $out/share/man/man1/
+    '';
+
+    outputs = [ "out" ];
+
+    doCheck = false;
+
+    meta.description = "man page for Clang ${version}";
+  });
+in self
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/clang/purity.patch b/nixpkgs/pkgs/development/compilers/llvm/8/clang/purity.patch
new file mode 100644
index 000000000000..b30d0d0b5d5b
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/clang/purity.patch
@@ -0,0 +1,30 @@
+From 4add81bba40dcec62c4ea4481be8e35ac53e89d8 Mon Sep 17 00:00:00 2001
+From: Will Dietz <w@wdtz.org>
+Date: Thu, 18 May 2017 11:56:12 -0500
+Subject: [PATCH] "purity" patch for 5.0
+
+---
+ lib/Driver/ToolChains/Gnu.cpp | 7 -------
+ 1 file changed, 7 deletions(-)
+
+diff --git a/lib/Driver/ToolChains/Gnu.cpp b/lib/Driver/ToolChains/Gnu.cpp
+index fe3c0191bb..c6a482bece 100644
+--- a/lib/Driver/ToolChains/Gnu.cpp
++++ b/lib/Driver/ToolChains/Gnu.cpp
+@@ -494,13 +494,6 @@ void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
+   if (!Args.hasArg(options::OPT_static)) {
+     if (Args.hasArg(options::OPT_rdynamic))
+       CmdArgs.push_back("-export-dynamic");
+-
+-    if (!Args.hasArg(options::OPT_shared)) {
+-      const std::string Loader =
+-          D.DyldPrefix + ToolChain.getDynamicLinker(Args);
+-      CmdArgs.push_back("-dynamic-linker");
+-      CmdArgs.push_back(Args.MakeArgString(Loader));
+-    }
+   }
+ 
+   CmdArgs.push_back("-o");
+-- 
+2.11.0
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/clang/static-pie.patch b/nixpkgs/pkgs/development/compilers/llvm/8/clang/static-pie.patch
new file mode 100644
index 000000000000..d1f86a162327
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/clang/static-pie.patch
@@ -0,0 +1,157 @@
+commit 7a9842bc92921e79b84630045276861be90b2d47
+Author: Siva Chandra <sivachandra@google.com>
+Date:   Wed Feb 20 19:07:04 2019 +0000
+
+    [Clang Driver] Add support for "-static-pie" argument to the Clang driver.
+    
+    Summary: This change mimics GCC's support for the "-static-pie" argument.
+    
+    Subscribers: cfe-commits
+    
+    Tags: #clang
+    
+    Differential Revision: https://reviews.llvm.org/D58307
+    
+    git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@354502 91177308-0d34-0410-b5e6-96231b3b80d8
+    (cherry picked from commit 7d6cd7825e6883f8650e32b07f3750824c2cef62)
+
+diff --git a/include/clang/Driver/Options.td b/include/clang/Driver/Options.td
+index d02d9744d7..75a21e66c7 100644
+--- a/include/clang/Driver/Options.td
++++ b/include/clang/Driver/Options.td
+@@ -2502,6 +2502,7 @@ def pthread : Flag<["-"], "pthread">, Flags<[CC1Option]>,
+ def no_pthread : Flag<["-"], "no-pthread">, Flags<[CC1Option]>;
+ def p : Flag<["-"], "p">;
+ def pie : Flag<["-"], "pie">;
++def static_pie : Flag<["-"], "static-pie">;
+ def read__only__relocs : Separate<["-"], "read_only_relocs">;
+ def remap : Flag<["-"], "remap">;
+ def rewrite_objc : Flag<["-"], "rewrite-objc">, Flags<[DriverOption,CC1Option]>,
+diff --git a/lib/Driver/ToolChains/CommonArgs.cpp b/lib/Driver/ToolChains/CommonArgs.cpp
+index d7e316befa..85ffc1618d 100644
+--- a/lib/Driver/ToolChains/CommonArgs.cpp
++++ b/lib/Driver/ToolChains/CommonArgs.cpp
+@@ -1138,19 +1138,22 @@ static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
+   bool isCygMing = Triple.isOSCygMing();
+   bool IsIAMCU = Triple.isOSIAMCU();
+   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
+-                      Args.hasArg(options::OPT_static);
++                      Args.hasArg(options::OPT_static) ||
++                      Args.hasArg(options::OPT_static_pie);
+ 
+   bool SharedLibgcc = Args.hasArg(options::OPT_shared_libgcc);
+   bool UnspecifiedLibgcc = !StaticLibgcc && !SharedLibgcc;
+ 
+   // Gcc adds libgcc arguments in various ways:
+   //
+-  // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed
+-  // g++ <none>:                   -lgcc_s               -lgcc
+-  // gcc shared:                   -lgcc_s               -lgcc
+-  // g++ shared:                   -lgcc_s               -lgcc
+-  // gcc static: -lgcc             -lgcc_eh
+-  // g++ static: -lgcc             -lgcc_eh
++  // gcc <none>:     -lgcc --as-needed -lgcc_s --no-as-needed
++  // g++ <none>:                       -lgcc_s               -lgcc
++  // gcc shared:                       -lgcc_s               -lgcc
++  // g++ shared:                       -lgcc_s               -lgcc
++  // gcc static:     -lgcc             -lgcc_eh
++  // g++ static:     -lgcc             -lgcc_eh
++  // gcc static-pie: -lgcc             -lgcc_eh
++  // g++ static-pie: -lgcc             -lgcc_eh
+   //
+   // Also, certain targets need additional adjustments.
+ 
+diff --git a/lib/Driver/ToolChains/Gnu.cpp b/lib/Driver/ToolChains/Gnu.cpp
+index 69dba8fec8..0faa0bb473 100644
+--- a/lib/Driver/ToolChains/Gnu.cpp
++++ b/lib/Driver/ToolChains/Gnu.cpp
+@@ -334,6 +334,7 @@ void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
+   const bool isAndroid = ToolChain.getTriple().isAndroid();
+   const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU();
+   const bool IsPIE = getPIE(Args, ToolChain);
++  const bool IsStaticPIE = Args.hasArg(options::OPT_static_pie);
+   const bool HasCRTBeginEndFiles =
+       ToolChain.getTriple().hasEnvironment() ||
+       (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
+@@ -354,6 +355,12 @@ void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
+   if (IsPIE)
+     CmdArgs.push_back("-pie");
+ 
++  if (IsStaticPIE) {
++    CmdArgs.push_back("-static");
++    CmdArgs.push_back("-pie");
++    CmdArgs.push_back("--no-dynamic-linker");
++  }
++
+   if (Args.hasArg(options::OPT_rdynamic))
+     CmdArgs.push_back("-export-dynamic");
+ 
+@@ -415,6 +422,8 @@ void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
+           crt1 = "gcrt1.o";
+         else if (IsPIE)
+           crt1 = "Scrt1.o";
++        else if (IsStaticPIE)
++          crt1 = "rcrt1.o";
+         else
+           crt1 = "crt1.o";
+       }
+@@ -432,7 +441,7 @@ void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
+         crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
+       else if (Args.hasArg(options::OPT_shared))
+         crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
+-      else if (IsPIE)
++      else if (IsPIE || IsStaticPIE)
+         crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
+       else
+         crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
+@@ -483,7 +492,7 @@ void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
+ 
+   if (!Args.hasArg(options::OPT_nostdlib)) {
+     if (!Args.hasArg(options::OPT_nodefaultlibs)) {
+-      if (Args.hasArg(options::OPT_static))
++      if (Args.hasArg(options::OPT_static) || IsStaticPIE)
+         CmdArgs.push_back("--start-group");
+ 
+       if (NeedsSanitizerDeps)
+@@ -518,7 +527,7 @@ void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
+       if (IsIAMCU)
+         CmdArgs.push_back("-lgloss");
+ 
+-      if (Args.hasArg(options::OPT_static))
++      if (Args.hasArg(options::OPT_static) || IsStaticPIE)
+         CmdArgs.push_back("--end-group");
+       else
+         AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
+@@ -535,7 +544,7 @@ void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
+       const char *crtend;
+       if (Args.hasArg(options::OPT_shared))
+         crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
+-      else if (IsPIE)
++      else if (IsPIE || IsStaticPIE)
+         crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
+       else
+         crtend = isAndroid ? "crtend_android.o" : "crtend.o";
+diff --git a/test/Driver/linux-ld.c b/test/Driver/linux-ld.c
+index 3ab81be490..800f782523 100644
+--- a/test/Driver/linux-ld.c
++++ b/test/Driver/linux-ld.c
+@@ -176,6 +176,19 @@
+ // CHECK-CLANG-NO-LIBGCC-STATIC: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
+ // CHECK-CLANG-NO-LIBGCC-STATIC: "--start-group" "-lgcc" "-lgcc_eh" "-lc" "--end-group"
+ //
++// RUN: %clang -static-pie -no-canonical-prefixes %s -### -o %t.o 2>&1 \
++// RUN:     --target=x86_64-unknown-linux -rtlib=platform \
++// RUN:     --gcc-toolchain="" \
++// RUN:     --sysroot=%S/Inputs/basic_linux_tree \
++// RUN:   | FileCheck --check-prefix=CHECK-CLANG-LD-STATIC-PIE %s
++// CHECK-CLANG-LD-STATIC-PIE: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]"
++// CHECK-CLANG-LD-STATIC-PIE: "-static"
++// CHECK-CLANG-LD-STATIC-PIE: "-pie"
++// CHECK-CLANG-LD-STATIC-PIE: "--no-dynamic-linker"
++// CHECK-CLANG-LD-STATIC-PIE: "-m" "elf_x86_64"
++// CHECK-CLANG-LD-STATIC-PIE: "{{.*}}rcrt1.o"
++// CHECK-CLANG-LD-STATIC-PIE: "--start-group" "-lgcc" "-lgcc_eh" "-lc" "--end-group"
++//
+ // RUN: %clang -dynamic -no-canonical-prefixes %s -### -o %t.o 2>&1 \
+ // RUN:     --target=x86_64-unknown-linux -rtlib=platform \
+ // RUN:     --gcc-toolchain="" \
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/clang/unwindlib.patch b/nixpkgs/pkgs/development/compilers/llvm/8/clang/unwindlib.patch
new file mode 100644
index 000000000000..6958fce60cef
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/clang/unwindlib.patch
@@ -0,0 +1,372 @@
+commit cd5603a4767277a29d3e67a9c3f2a5d2129cd973
+Author: Sterling Augustine <saugustine@google.com>
+Date:   Tue Mar 19 20:01:59 2019 +0000
+
+    Add --unwindlib=[libgcc|compiler-rt] to parallel --rtlib= [take 2]
+    
+    "clang++ hello.cc --rtlib=compiler-rt"
+    
+    now can works without specifying additional unwind or exception
+    handling libraries.
+    
+    This reworked version of the feature no longer modifies today's default
+    unwind library for compiler-rt: which is nothing. Rather, a user
+    can specify -DCLANG_DEFAULT_UNWINDLIB=libunwind when configuring
+    the compiler.
+    
+    This should address the issues from the previous version.
+    
+    Update tests for new --unwindlib semantics.
+    
+    Differential Revision: https://reviews.llvm.org/D59109
+    
+    git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@356508 91177308-0d34-0410-b5e6-96231b3b80d8
+    (cherry picked from commit 344aa82a52f2fae527f58284567ae305a314f7a8)
+
+diff --git a/CMakeLists.txt b/CMakeLists.txt
+index c2016a45ca..edeb2b66a1 100644
+--- a/CMakeLists.txt
++++ b/CMakeLists.txt
+@@ -261,6 +261,24 @@ if (NOT(CLANG_DEFAULT_RTLIB STREQUAL "" OR
+     "Default runtime library to use (\"libgcc\" or \"compiler-rt\", empty for platform default)" FORCE)
+ endif()
+ 
++set(CLANG_DEFAULT_UNWINDLIB "" CACHE STRING
++  "Default unwind library to use (\"none\" \"libgcc\" or \"libunwind\", empty to match runtime library.)")
++if (CLANG_DEFAULT_UNWINDLIB STREQUAL "")
++  if (CLANG_DEFAULT_RTLIB STREQUAL "libgcc")
++    set (CLANG_DEFAULT_UNWINDLIB "libgcc" CACHE STRING "" FORCE)
++  elseif (CLANG_DEFAULT_RTLIBS STREQUAL "libunwind")
++    set (CLANG_DEFAULT_UNWINDLIB "none" CACHE STRING "" FORCE)
++  endif()
++endif()
++
++if (NOT(CLANG_DEFAULT_UNWINDLIB STREQUAL "none" OR
++        CLANG_DEFAULT_UNWINDLIB STREQUAL "libgcc" OR
++        CLANG_DEFAULT_UNWINDLIB STREQUAL "libunwind"))
++  message(WARNING "Resetting default unwindlib to use platform default")
++  set(CLANG_DEFAULT_UNWINDLIB "" CACHE STRING
++    "Default unwind library to use (\"none\" \"libgcc\" or \"libunwind\", empty for none)" FORCE)
++endif()
++
+ set(CLANG_DEFAULT_OBJCOPY "objcopy" CACHE STRING
+   "Default objcopy executable to use.")
+ 
+diff --git a/include/clang/Basic/DiagnosticDriverKinds.td b/include/clang/Basic/DiagnosticDriverKinds.td
+index 5475e28ed7..15971210e4 100644
+--- a/include/clang/Basic/DiagnosticDriverKinds.td
++++ b/include/clang/Basic/DiagnosticDriverKinds.td
+@@ -52,6 +52,10 @@ def err_drv_invalid_rtlib_name : Error<
+   "invalid runtime library name in argument '%0'">;
+ def err_drv_unsupported_rtlib_for_platform : Error<
+   "unsupported runtime library '%0' for platform '%1'">;
++def err_drv_invalid_unwindlib_name : Error<
++  "invalid unwind library name in argument '%0'">;
++def err_drv_incompatible_unwindlib : Error<
++  "--rtlib=libgcc requires --unwindlib=libgcc">;
+ def err_drv_invalid_stdlib_name : Error<
+   "invalid library name in argument '%0'">;
+ def err_drv_invalid_output_with_multiple_archs : Error<
+diff --git a/include/clang/Config/config.h.cmake b/include/clang/Config/config.h.cmake
+index 1d624450b9..2d4cb747e8 100644
+--- a/include/clang/Config/config.h.cmake
++++ b/include/clang/Config/config.h.cmake
+@@ -23,6 +23,9 @@
+ /* Default runtime library to use. */
+ #define CLANG_DEFAULT_RTLIB "${CLANG_DEFAULT_RTLIB}"
+ 
++/* Default unwind library to use. */
++#define CLANG_DEFAULT_UNWINDLIB "${CLANG_DEFAULT_UNWINDLIB}"
++
+ /* Default objcopy to use */
+ #define CLANG_DEFAULT_OBJCOPY "${CLANG_DEFAULT_OBJCOPY}"
+ 
+diff --git a/include/clang/Driver/Options.td b/include/clang/Driver/Options.td
+index 75a21e66c7..4da0e54965 100644
+--- a/include/clang/Driver/Options.td
++++ b/include/clang/Driver/Options.td
+@@ -2570,6 +2570,8 @@ def std_EQ : Joined<["-", "--"], "std=">, Flags<[CC1Option]>,
+   }]>;
+ def stdlib_EQ : Joined<["-", "--"], "stdlib=">, Flags<[CC1Option]>,
+   HelpText<"C++ standard library to use">, Values<"libc++,libstdc++,platform">;
++def unwindlib_EQ : Joined<["-", "--"], "unwindlib=">, Flags<[CC1Option]>,
++  HelpText<"Unwind library to use">, Values<"libgcc,unwindlib,platform">;
+ def sub__library : JoinedOrSeparate<["-"], "sub_library">;
+ def sub__umbrella : JoinedOrSeparate<["-"], "sub_umbrella">;
+ def system_header_prefix : Joined<["--"], "system-header-prefix=">,
+diff --git a/include/clang/Driver/ToolChain.h b/include/clang/Driver/ToolChain.h
+index d5f75b8271..4bedf760eb 100644
+--- a/include/clang/Driver/ToolChain.h
++++ b/include/clang/Driver/ToolChain.h
+@@ -100,6 +100,12 @@ public:
+     RLT_Libgcc
+   };
+ 
++  enum UnwindLibType {
++    UNW_None,
++    UNW_CompilerRT,
++    UNW_Libgcc
++  };
++
+   enum RTTIMode {
+     RM_Enabled,
+     RM_Disabled,
+@@ -368,6 +374,10 @@ public:
+     return ToolChain::CST_Libstdcxx;
+   }
+ 
++  virtual UnwindLibType GetDefaultUnwindLibType() const {
++    return ToolChain::UNW_None;
++  }
++
+   virtual std::string getCompilerRTPath() const;
+ 
+   virtual std::string getCompilerRT(const llvm::opt::ArgList &Args,
+@@ -512,6 +522,10 @@ public:
+   // given compilation arguments.
+   virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const;
+ 
++  // GetUnwindLibType - Determine the unwind library type to use with the
++  // given compilation arguments.
++  virtual UnwindLibType GetUnwindLibType(const llvm::opt::ArgList &Args) const;
++
+   /// AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set
+   /// the include paths to use for the given C++ standard library type.
+   virtual void
+diff --git a/lib/Driver/ToolChain.cpp b/lib/Driver/ToolChain.cpp
+index 88a627eab6..d82423f4a8 100644
+--- a/lib/Driver/ToolChain.cpp
++++ b/lib/Driver/ToolChain.cpp
+@@ -680,6 +680,33 @@ ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
+   return GetDefaultRuntimeLibType();
+ }
+ 
++ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
++    const ArgList &Args) const {
++  const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
++  StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
++
++  if (LibName == "none")
++    return ToolChain::UNW_None;
++  else if (LibName == "platform" || LibName == "") {
++    ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
++    if (RtLibType == ToolChain::RLT_CompilerRT)
++      return ToolChain::UNW_None;
++    else if (RtLibType == ToolChain::RLT_Libgcc)
++      return ToolChain::UNW_Libgcc;
++  } else if (LibName == "libunwind") {
++    if (GetRuntimeLibType(Args) == RLT_Libgcc)
++      getDriver().Diag(diag::err_drv_incompatible_unwindlib);
++    return ToolChain::UNW_CompilerRT;
++  } else if (LibName == "libgcc")
++    return ToolChain::UNW_Libgcc;
++
++  if (A)
++    getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
++        << A->getAsString(Args);
++
++  return GetDefaultUnwindLibType();
++}
++
+ ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
+   const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
+   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
+diff --git a/lib/Driver/ToolChains/CommonArgs.cpp b/lib/Driver/ToolChains/CommonArgs.cpp
+index 85ffc1618d..9fd29726a4 100644
+--- a/lib/Driver/ToolChains/CommonArgs.cpp
++++ b/lib/Driver/ToolChains/CommonArgs.cpp
+@@ -1132,47 +1132,80 @@ bool tools::isObjCAutoRefCount(const ArgList &Args) {
+   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
+ }
+ 
+-static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
+-                      ArgStringList &CmdArgs, const ArgList &Args) {
+-  bool isAndroid = Triple.isAndroid();
+-  bool isCygMing = Triple.isOSCygMing();
+-  bool IsIAMCU = Triple.isOSIAMCU();
+-  bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
+-                      Args.hasArg(options::OPT_static) ||
+-                      Args.hasArg(options::OPT_static_pie);
+-
+-  bool SharedLibgcc = Args.hasArg(options::OPT_shared_libgcc);
+-  bool UnspecifiedLibgcc = !StaticLibgcc && !SharedLibgcc;
+-
+-  // Gcc adds libgcc arguments in various ways:
+-  //
+-  // gcc <none>:     -lgcc --as-needed -lgcc_s --no-as-needed
+-  // g++ <none>:                       -lgcc_s               -lgcc
+-  // gcc shared:                       -lgcc_s               -lgcc
+-  // g++ shared:                       -lgcc_s               -lgcc
+-  // gcc static:     -lgcc             -lgcc_eh
+-  // g++ static:     -lgcc             -lgcc_eh
+-  // gcc static-pie: -lgcc             -lgcc_eh
+-  // g++ static-pie: -lgcc             -lgcc_eh
+-  //
+-  // Also, certain targets need additional adjustments.
++enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
++
++static LibGccType getLibGccType(const ArgList &Args) {
++  bool Static = Args.hasArg(options::OPT_static_libgcc) ||
++                Args.hasArg(options::OPT_static) ||
++                Args.hasArg(options::OPT_static_pie);
++
++  bool Shared = Args.hasArg(options::OPT_shared_libgcc);
++  if (Shared)
++    return LibGccType::SharedLibGcc;
++  if (Static)
++    return LibGccType::StaticLibGcc;
++  return LibGccType::UnspecifiedLibGcc;
++}
+ 
+-  bool LibGccFirst = (D.CCCIsCC() && UnspecifiedLibgcc) || StaticLibgcc;
+-  if (LibGccFirst)
+-    CmdArgs.push_back("-lgcc");
++// Gcc adds libgcc arguments in various ways:
++//
++// gcc <none>:     -lgcc --as-needed -lgcc_s --no-as-needed
++// g++ <none>:                       -lgcc_s               -lgcc
++// gcc shared:                       -lgcc_s               -lgcc
++// g++ shared:                       -lgcc_s               -lgcc
++// gcc static:     -lgcc             -lgcc_eh
++// g++ static:     -lgcc             -lgcc_eh
++// gcc static-pie: -lgcc             -lgcc_eh
++// g++ static-pie: -lgcc             -lgcc_eh
++//
++// Also, certain targets need additional adjustments.
++
++static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
++                             ArgStringList &CmdArgs, const ArgList &Args) {
++  ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
++  // Targets that don't use unwind libraries.
++  if (TC.getTriple().isAndroid() || TC.getTriple().isOSIAMCU() ||
++      TC.getTriple().isOSBinFormatWasm() ||
++      UNW == ToolChain::UNW_None)
++    return;
+ 
+-  bool AsNeeded = D.CCCIsCC() && UnspecifiedLibgcc && !isAndroid && !isCygMing;
++  LibGccType LGT = getLibGccType(Args);
++  bool AsNeeded = D.CCCIsCC() && LGT == LibGccType::UnspecifiedLibGcc &&
++                  !TC.getTriple().isAndroid() && !TC.getTriple().isOSCygMing();
+   if (AsNeeded)
+     CmdArgs.push_back("--as-needed");
+ 
+-  if ((UnspecifiedLibgcc || SharedLibgcc) && !isAndroid)
+-    CmdArgs.push_back("-lgcc_s");
+-
+-  else if (StaticLibgcc && !isAndroid && !IsIAMCU)
+-    CmdArgs.push_back("-lgcc_eh");
++  switch (UNW) {
++  case ToolChain::UNW_None:
++    return;
++  case ToolChain::UNW_Libgcc: {
++    LibGccType LGT = getLibGccType(Args);
++    if (LGT == LibGccType::UnspecifiedLibGcc || LGT == LibGccType::SharedLibGcc)
++      CmdArgs.push_back("-lgcc_s");
++    else if (LGT == LibGccType::StaticLibGcc)
++      CmdArgs.push_back("-lgcc_eh");
++    break;
++  }
++  case ToolChain::UNW_CompilerRT:
++    CmdArgs.push_back("-lunwind");
++    break;
++  }
+ 
+   if (AsNeeded)
+     CmdArgs.push_back("--no-as-needed");
++}
++
++static void AddLibgcc(const ToolChain &TC, const Driver &D,
++                      ArgStringList &CmdArgs, const ArgList &Args) {
++  bool isAndroid = TC.getTriple().isAndroid();
++
++  LibGccType LGT = getLibGccType(Args);
++  bool LibGccFirst = (D.CCCIsCC() && LGT == LibGccType::UnspecifiedLibGcc) ||
++                     LGT == LibGccType::StaticLibGcc;
++  if (LibGccFirst)
++    CmdArgs.push_back("-lgcc");
++
++  AddUnwindLibrary(TC, D, CmdArgs, Args);
+ 
+   if (!LibGccFirst)
+     CmdArgs.push_back("-lgcc");
+@@ -1182,7 +1215,7 @@ static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
+   //
+   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
+   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
+-  if (isAndroid && !StaticLibgcc)
++  if (isAndroid && getLibGccType(Args) != LibGccType::StaticLibGcc)
+     CmdArgs.push_back("-ldl");
+ }
+ 
+@@ -1194,6 +1227,7 @@ void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
+   switch (RLT) {
+   case ToolChain::RLT_CompilerRT:
+     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
++    AddUnwindLibrary(TC, D, CmdArgs, Args);
+     break;
+   case ToolChain::RLT_Libgcc:
+     // Make sure libgcc is not used under MSVC environment by default
+@@ -1205,7 +1239,7 @@ void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
+             << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
+       }
+     } else
+-      AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
++      AddLibgcc(TC, D, CmdArgs, Args);
+     break;
+   }
+ }
+diff --git a/test/Driver/compiler-rt-unwind.c b/test/Driver/compiler-rt-unwind.c
+new file mode 100644
+index 0000000000..00024dfa7e
+--- /dev/null
++++ b/test/Driver/compiler-rt-unwind.c
+@@ -0,0 +1,49 @@
++// General tests that the driver handles combinations of --rtlib=XXX and
++// --unwindlib=XXX properly.
++//
++// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
++// RUN:     --target=x86_64-unknown-linux \
++// RUN:     --gcc-toolchain="" \
++// RUN:   | FileCheck --check-prefix=RTLIB-EMPTY %s
++// RTLIB-EMPTY: "{{.*}}lgcc"
++// RTLIB-EMPTY: "{{.*}}-lgcc_s"
++//
++// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
++// RUN:     --target=x86_64-unknown-linux -rtlib=libgcc \
++// RUN:     --gcc-toolchain="" \
++// RUN:   | FileCheck --check-prefix=RTLIB-GCC %s
++// RTLIB-GCC: "{{.*}}lgcc"
++// RTLIB-GCC: "{{.*}}lgcc_s"
++//
++// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
++// RUN:     --target=x86_64-unknown-linux -rtlib=libgcc --unwindlib=libunwind \
++// RUN:     --gcc-toolchain="" \
++// RUN:   | FileCheck --check-prefix=RTLIB-GCC-UNWINDLIB-COMPILER-RT %s
++// RTLIB-GCC-UNWINDLIB-COMPILER-RT: "{{.*}}lgcc"
++// RTLIB-GCC-UNWINDLIB-COMPILER-RT: "{{.*}}lunwind"
++//
++// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1   \
++// RUN:     --target=x86_64-unknown-linux -rtlib=compiler-rt \
++// RUN:     --gcc-toolchain="" \
++// RUN:   | FileCheck --check-prefix=RTLIB-COMPILER-RT %s
++// RTLIB-COMPILER-RT: "{{.*}}libclang_rt.builtins-x86_64.a"
++//
++// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1   \
++// RUN:     --target=x86_64-unknown-linux -rtlib=compiler-rt --unwindlib=libgcc \
++// RUN:     --gcc-toolchain="" \
++// RUN:   | FileCheck --check-prefix=RTLIB-COMPILER-RT-UNWINDLIB-GCC %s
++// RTLIB-COMPILER-RT-UNWINDLIB-GCC: "{{.*}}libclang_rt.builtins-x86_64.a"
++// RTLIB-COMPILER-RT-UNWINDLIB-GCC: "{{.*}}lgcc_s"
++//
++// RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1              \
++// RUN:     --target=x86_64-unknown-linux -rtlib=compiler-rt --unwindlib=libgcc \
++// RUN:     -static --gcc-toolchain="" \
++// RUN:   | FileCheck --check-prefix=RTLIB-COMPILER-RT-UNWINDLIB-GCC-STATIC %s
++// RTLIB-COMPILER-RT-UNWINDLIB-GCC-STATIC: "{{.*}}libclang_rt.builtins-x86_64.a"
++// RTLIB-COMPILER-RT-UNWINDLIB-GCC-STATIC: "{{.*}}lgcc_eh"
++//
++// RUN: not %clang -no-canonical-prefixes %s -o %t.o 2> %t.err              \
++// RUN:     --target=x86_64-unknown-linux -rtlib=libgcc --unwindlib=libunwind \
++// RUN:     --gcc-toolchain="" \
++// RUN: FileCheck --input-file=%t.err --check-prefix=RTLIB-GCC-UNWINDLIB-COMPILER_RT %s
++// RTLIB-GCC-UNWINDLIB-COMPILER_RT: "{{[.|\\\n]*}}--rtlib=libgcc requires --unwindlib=libgcc"
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/compiler-rt-clock_gettime.patch b/nixpkgs/pkgs/development/compilers/llvm/8/compiler-rt-clock_gettime.patch
new file mode 100644
index 000000000000..f9323ed95c05
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/compiler-rt-clock_gettime.patch
@@ -0,0 +1,74 @@
+commit f00c7bccf7955b7dfbb4859fd9019e9eb3349f2d
+Author: Tobias Mayer <tobim@fastmail.fm>
+Date:   Wed Feb 13 12:44:17 2019 +0100
+
+    Provide clock_gettime for xray on macos < 10.12
+
+diff --git a/lib/xray/xray_basic_logging.cc b/lib/xray/xray_basic_logging.cc
+index a46c151af..38aea6932 100644
+--- a/lib/xray/xray_basic_logging.cc
++++ b/lib/xray/xray_basic_logging.cc
+@@ -36,6 +36,29 @@
+ #include "xray_tsc.h"
+ #include "xray_utils.h"
+ 
++#if __MACH__
++#include <mach/clock.h>
++#include <mach/mach.h>
++enum clockid_t {
++    CLOCK_MONOTONIC = REALTIME_CLOCK,
++    CLOCK_REALTIME = REALTIME_CLOCK
++};
++
++int clock_gettime(clockid_t clock_id, struct timespec *ts) {
++  if (ts != NULL) {
++      clock_serv_t cclock;
++      mach_timespec_t mts;
++      host_get_clock_service(mach_host_self(), clock_id, &cclock);
++      clock_get_time(cclock, &mts);
++      mach_port_deallocate(mach_task_self(), cclock);
++      ts->tv_sec = mts.tv_sec;
++      ts->tv_nsec = mts.tv_nsec;
++      return 0;
++  }
++  return -1;
++}
++#endif
++
+ namespace __xray {
+ 
+ SpinMutex LogMutex;
+diff --git a/lib/xray/xray_fdr_logging.cc b/lib/xray/xray_fdr_logging.cc
+index 4b308b27f..1d044c8fd 100644
+--- a/lib/xray/xray_fdr_logging.cc
++++ b/lib/xray/xray_fdr_logging.cc
+@@ -38,6 +38,29 @@
+ #include "xray_tsc.h"
+ #include "xray_utils.h"
+ 
++#if __MACH__
++#include <mach/clock.h>
++#include <mach/mach.h>
++enum clockid_t {
++    CLOCK_MONOTONIC = REALTIME_CLOCK,
++    CLOCK_REALTIME = REALTIME_CLOCK
++};
++
++int clock_gettime(clockid_t clock_id, struct timespec *ts) {
++  if (ts != NULL) {
++      clock_serv_t cclock;
++      mach_timespec_t mts;
++      host_get_clock_service(mach_host_self(), clock_id, &cclock);
++      clock_get_time(cclock, &mts);
++      mach_port_deallocate(mach_task_self(), cclock);
++      ts->tv_sec = mts.tv_sec;
++      ts->tv_nsec = mts.tv_nsec;
++      return 0;
++  }
++  return -1;
++}
++#endif
++
+ namespace __xray {
+ 
+ atomic_sint32_t LoggingStatus = {XRayLogInitStatus::XRAY_LOG_UNINITIALIZED};
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/compiler-rt-codesign.patch b/nixpkgs/pkgs/development/compilers/llvm/8/compiler-rt-codesign.patch
new file mode 100644
index 000000000000..3cc12b94b200
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/compiler-rt-codesign.patch
@@ -0,0 +1,33 @@
+From 3dec5f3475a26aeb4678627795c4b67c6b7b4785 Mon Sep 17 00:00:00 2001
+From: Will Dietz <w@wdtz.org>
+Date: Tue, 19 Sep 2017 13:13:06 -0500
+Subject: [PATCH] remove codesign use on Apple, disable ios sim testing that
+ needs it
+
+---
+ cmake/Modules/AddCompilerRT.cmake |  8 ------
+ test/asan/CMakeLists.txt          | 52 ---------------------------------------
+ test/tsan/CMakeLists.txt          | 47 -----------------------------------
+ 3 files changed, 107 deletions(-)
+
+diff --git a/cmake/Modules/AddCompilerRT.cmake b/cmake/Modules/AddCompilerRT.cmake
+index bc5fb9ff7..b64eb4246 100644
+--- a/cmake/Modules/AddCompilerRT.cmake
++++ b/cmake/Modules/AddCompilerRT.cmake
+@@ -210,14 +210,6 @@ function(add_compiler_rt_runtime name type)
+         set_target_properties(${libname} PROPERTIES IMPORT_PREFIX "")
+         set_target_properties(${libname} PROPERTIES IMPORT_SUFFIX ".lib")
+       endif()
+-      if(APPLE)
+-        # Ad-hoc sign the dylibs
+-        add_custom_command(TARGET ${libname}
+-          POST_BUILD  
+-          COMMAND codesign --sign - $<TARGET_FILE:${libname}>
+-          WORKING_DIRECTORY ${COMPILER_RT_LIBRARY_OUTPUT_DIR}
+-        )
+-      endif()
+     endif()
+     install(TARGETS ${libname}
+       ARCHIVE DESTINATION ${COMPILER_RT_LIBRARY_INSTALL_DIR}
+2.14.1
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/compiler-rt.nix b/nixpkgs/pkgs/development/compilers/llvm/8/compiler-rt.nix
new file mode 100644
index 000000000000..47c8b7bd59f5
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/compiler-rt.nix
@@ -0,0 +1,66 @@
+{ stdenv, version, fetch, cmake, python, llvm, libcxxabi }:
+stdenv.mkDerivation rec {
+  name = "compiler-rt-${version}";
+  inherit version;
+  src = fetch "compiler-rt" "1c919wsm17xnv7lr8bhpq2wkq8113lzlw6hzhfr737j59x3wfddl";
+
+  nativeBuildInputs = [ cmake python llvm ];
+  buildInputs = stdenv.lib.optional stdenv.hostPlatform.isDarwin libcxxabi;
+
+  cmakeFlags = [
+    "-DCOMPILER_RT_DEFAULT_TARGET_ONLY=ON"
+    "-DCMAKE_C_COMPILER_TARGET=${stdenv.hostPlatform.config}"
+    "-DCMAKE_ASM_COMPILER_TARGET=${stdenv.hostPlatform.config}"
+  ] ++ stdenv.lib.optionals (stdenv.hostPlatform != stdenv.buildPlatform) [
+    "-DCMAKE_C_FLAGS=-nodefaultlibs"
+    "-DCMAKE_CXX_COMPILER_WORKS=ON"
+    "-DCOMPILER_RT_BUILD_SANITIZERS=OFF"
+    "-DCOMPILER_RT_BUILD_XRAY=OFF"
+    "-DCOMPILER_RT_BUILD_LIBFUZZER=OFF"
+    "-DCOMPILER_RT_BUILD_PROFILE=OFF"
+    "-DCOMPILER_RT_BAREMETAL_BUILD=ON"
+    "-DCMAKE_SIZEOF_VOID_P=${toString (stdenv.hostPlatform.parsed.cpu.bits / 8)}"
+  ] ++ stdenv.lib.optionals stdenv.hostPlatform.isMusl [
+    "-DCOMPILER_RT_BUILD_SANITIZERS=OFF"
+    "-DCOMPILER_RT_BUILD_XRAY=OFF"
+    "-DCOMPILER_RT_BUILD_LIBFUZZER=OFF"
+    "-DCOMPILER_RT_BUILD_PROFILE=OFF"
+  ];
+
+  outputs = [ "out" "dev" ];
+
+  patches = [
+    ./compiler-rt-codesign.patch # Revert compiler-rt commit that makes codesign mandatory
+  ]# ++ stdenv.lib.optional stdenv.hostPlatform.isMusl ./sanitizers-nongnu.patch
+    ++ stdenv.lib.optional (stdenv.hostPlatform != stdenv.buildPlatform) ./crtbegin-and-end.patch
+    ++ stdenv.lib.optional stdenv.hostPlatform.isDarwin ./compiler-rt-clock_gettime.patch;
+
+  # TSAN requires XPC on Darwin, which we have no public/free source files for. We can depend on the Apple frameworks
+  # to get it, but they're unfree. Since LLVM is rather central to the stdenv, we patch out TSAN support so that Hydra
+  # can build this. If we didn't do it, basically the entire nixpkgs on Darwin would have an unfree dependency and we'd
+  # get no binary cache for the entire platform. If you really find yourself wanting the TSAN, make this controllable by
+  # a flag and turn the flag off during the stdenv build.
+  postPatch = stdenv.lib.optionalString stdenv.isDarwin ''
+    substituteInPlace cmake/config-ix.cmake \
+      --replace 'set(COMPILER_RT_HAS_TSAN TRUE)' 'set(COMPILER_RT_HAS_TSAN FALSE)'
+  '' + stdenv.lib.optionalString (stdenv.hostPlatform != stdenv.buildPlatform) ''
+    substituteInPlace lib/builtins/int_util.c \
+      --replace "#include <stdlib.h>" ""
+    substituteInPlace lib/builtins/clear_cache.c \
+      --replace "#include <assert.h>" ""
+    substituteInPlace lib/builtins/cpu_model.c \
+      --replace "#include <assert.h>" ""
+  '';
+
+  # Hack around weird upsream RPATH bug
+  postInstall = stdenv.lib.optionalString stdenv.isDarwin ''
+    ln -s "$out/lib"/*/* "$out/lib"
+  '' + stdenv.lib.optionalString (stdenv.hostPlatform.useLLVM or false) ''
+    ln -s $out/lib/*/clang_rt.crtbegin-*.o $out/lib/crtbegin.o
+    ln -s $out/lib/*/clang_rt.crtend-*.o $out/lib/crtend.o
+    ln -s $out/lib/*/clang_rt.crtbegin_shared-*.o $out/lib/crtbeginS.o
+    ln -s $out/lib/*/clang_rt.crtend_shared-*.o $out/lib/crtendS.o
+  '';
+
+  enableParallelBuilding = true;
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/crtbegin-and-end.patch b/nixpkgs/pkgs/development/compilers/llvm/8/crtbegin-and-end.patch
new file mode 100644
index 000000000000..e63be181f95c
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/crtbegin-and-end.patch
@@ -0,0 +1,595 @@
+Get crtbegin and crtend without compiler GCC! PR is at https://reviews.llvm.org/D28791
+
+Index: compiler-rt/CMakeLists.txt
+===================================================================
+--- compiler-rt/CMakeLists.txt
++++ compiler-rt/CMakeLists.txt
+@@ -29,6 +29,8 @@
+ 
+ option(COMPILER_RT_BUILD_BUILTINS "Build builtins" ON)
+ mark_as_advanced(COMPILER_RT_BUILD_BUILTINS)
++option(COMPILER_RT_BUILD_CRT "Build crtbegin.o/crtend.o" ON)
++mark_as_advanced(COMPILER_RT_BUILD_CRT)
+ option(COMPILER_RT_BUILD_SANITIZERS "Build sanitizers" ON)
+ mark_as_advanced(COMPILER_RT_BUILD_SANITIZERS)
+ option(COMPILER_RT_BUILD_XRAY "Build xray" ON)
+Index: compiler-rt/cmake/Modules/AddCompilerRT.cmake
+===================================================================
+--- compiler-rt/cmake/Modules/AddCompilerRT.cmake
++++ compiler-rt/cmake/Modules/AddCompilerRT.cmake
+@@ -132,7 +132,7 @@
+ # Adds static or shared runtime for a list of architectures and operating
+ # systems and puts it in the proper directory in the build and install trees.
+ # add_compiler_rt_runtime(<name>
+-#                         {STATIC|SHARED}
++#                         {OBJECT|STATIC|SHARED}
+ #                         ARCHS <architectures>
+ #                         OS <os list>
+ #                         SOURCES <source files>
+@@ -144,8 +144,8 @@
+ #                         PARENT_TARGET <convenience parent target>
+ #                         ADDITIONAL_HEADERS <header files>)
+ function(add_compiler_rt_runtime name type)
+-  if(NOT type MATCHES "^(STATIC|SHARED)$")
+-    message(FATAL_ERROR "type argument must be STATIC or SHARED")
++  if(NOT type MATCHES "^(OBJECT|STATIC|SHARED)$")
++    message(FATAL_ERROR "type argument must be OBJECT, STATIC or SHARED")
+     return()
+   endif()
+   cmake_parse_arguments(LIB
+@@ -204,7 +204,10 @@
+         message(FATAL_ERROR "Architecture ${arch} can't be targeted")
+         return()
+       endif()
+-      if(type STREQUAL "STATIC")
++      if(type STREQUAL "OBJECT")
++        set(libname "${name}-${arch}")
++        set(output_name_${libname} ${libname}${COMPILER_RT_OS_SUFFIX})
++      elseif(type STREQUAL "STATIC")
+         set(libname "${name}-${arch}")
+         set_output_name(output_name_${libname} ${name} ${arch})
+       else()
+@@ -270,12 +273,34 @@
+       set(COMPONENT_OPTION COMPONENT ${libname})
+     endif()
+ 
+-    add_library(${libname} ${type} ${sources_${libname}})
+-    set_target_compile_flags(${libname} ${extra_cflags_${libname}})
+-    set_target_link_flags(${libname} ${extra_link_flags_${libname}})
+-    set_property(TARGET ${libname} APPEND PROPERTY
+-                COMPILE_DEFINITIONS ${LIB_DEFS})
+-    set_target_output_directories(${libname} ${output_dir_${libname}})
++    if(type STREQUAL "OBJECT")
++      string(TOUPPER ${CMAKE_BUILD_TYPE} config)
++      get_property(cflags SOURCE ${sources_${libname}} PROPERTY COMPILE_FLAGS)
++      separate_arguments(cflags)
++      add_custom_command(
++          OUTPUT ${output_dir_${libname}}/${libname}.o
++          COMMAND ${CMAKE_C_COMPILER} ${sources_${libname}} ${cflags} ${extra_cflags_${libname}} -c -o ${output_dir_${libname}}/${libname}.o
++          DEPENDS ${sources_${libname}}
++          COMMENT "Building C object ${libname}.o")
++      add_custom_target(${libname} DEPENDS ${output_dir_${libname}}/${libname}.o)
++      install(FILES ${output_dir_${libname}}/${libname}.o
++        DESTINATION ${install_dir_${libname}}
++        ${COMPONENT_OPTION})
++    else()
++      add_library(${libname} ${type} ${sources_${libname}})
++      set_target_compile_flags(${libname} ${extra_cflags_${libname}})
++      set_target_link_flags(${libname} ${extra_link_flags_${libname}})
++      set_property(TARGET ${libname} APPEND PROPERTY
++                   COMPILE_DEFINITIONS ${LIB_DEFS})
++      set_target_output_directories(${libname} ${output_dir_${libname}})
++      install(TARGETS ${libname}
++        ARCHIVE DESTINATION ${install_dir_${libname}}
++                ${COMPONENT_OPTION}
++        LIBRARY DESTINATION ${install_dir_${libname}}
++                ${COMPONENT_OPTION}
++        RUNTIME DESTINATION ${install_dir_${libname}}
++                ${COMPONENT_OPTION})
++    endif()
+     set_target_properties(${libname} PROPERTIES
+         OUTPUT_NAME ${output_name_${libname}})
+     set_target_properties(${libname} PROPERTIES FOLDER "Compiler-RT Runtime")
+@@ -299,13 +324,6 @@
+         )
+       endif()
+     endif()
+-    install(TARGETS ${libname}
+-      ARCHIVE DESTINATION ${install_dir_${libname}}
+-              ${COMPONENT_OPTION}
+-      LIBRARY DESTINATION ${install_dir_${libname}}
+-              ${COMPONENT_OPTION}
+-      RUNTIME DESTINATION ${install_dir_${libname}}
+-              ${COMPONENT_OPTION})
+ 
+     # We only want to generate per-library install targets if you aren't using
+     # an IDE because the extra targets get cluttered in IDEs.
+Index: compiler-rt/cmake/config-ix.cmake
+===================================================================
+--- compiler-rt/cmake/config-ix.cmake
++++ compiler-rt/cmake/config-ix.cmake
+@@ -227,6 +227,7 @@
+     ${ARM32} ${ARM64} ${MIPS32} ${MIPS64} ${S390X})
+ set(ALL_ASAN_SUPPORTED_ARCH ${X86} ${X86_64} ${ARM32} ${ARM64}
+     ${MIPS32} ${MIPS64} ${PPC64} ${S390X})
++set(ALL_CRT_SUPPORTED_ARCH ${X86} ${X86_64} ${ARM32} ${ARM64})
+ set(ALL_DFSAN_SUPPORTED_ARCH ${X86_64} ${MIPS64} ${ARM64})
+ set(ALL_FUZZER_SUPPORTED_ARCH ${X86_64} ${ARM64})
+ 
+@@ -474,6 +475,7 @@
+     SANITIZER_COMMON_SUPPORTED_ARCH)
+ 
+ else()
++  filter_available_targets(CRT_SUPPORTED_ARCH ${ALL_CRT_SUPPORTED_ARCH})
+   # Architectures supported by compiler-rt libraries.
+   filter_available_targets(SANITIZER_COMMON_SUPPORTED_ARCH
+     ${ALL_SANITIZER_COMMON_SUPPORTED_ARCH})
+@@ -563,6 +565,12 @@
+ 
+ # TODO: Add builtins support.
+ 
++if (CRT_SUPPORTED_ARCH AND OS_NAME MATCHES "Linux")
++  set(COMPILER_RT_HAS_CRT TRUE)
++else()
++  set(COMPILER_RT_HAS_CRT FALSE)
++endif()
++
+ if (COMPILER_RT_HAS_SANITIZER_COMMON AND DFSAN_SUPPORTED_ARCH AND
+     OS_NAME MATCHES "Linux")
+   set(COMPILER_RT_HAS_DFSAN TRUE)
+Index: compiler-rt/lib/CMakeLists.txt
+===================================================================
+--- compiler-rt/lib/CMakeLists.txt
++++ compiler-rt/lib/CMakeLists.txt
+@@ -17,6 +17,10 @@
+   add_subdirectory(builtins)
+ endif()
+ 
++if(COMPILER_RT_BUILD_CRT)
++  add_subdirectory(crt)
++endif()
++
+ function(compiler_rt_build_runtime runtime)
+   string(TOUPPER ${runtime} runtime_uppercase)
+   if(COMPILER_RT_HAS_${runtime_uppercase})
+Index: compiler-rt/lib/crt/CMakeLists.txt
+===================================================================
+--- /dev/null
++++ compiler-rt/lib/crt/CMakeLists.txt
+@@ -0,0 +1,102 @@
++add_compiler_rt_component(crt)
++
++function(check_cxx_section_exists section output)
++  cmake_parse_arguments(ARG "" "" "SOURCE;FLAGS" ${ARGN})
++  if(NOT ARG_SOURCE)
++    set(ARG_SOURCE "int main() { return 0; }\n")
++  endif()
++
++  string(RANDOM TARGET_NAME)
++  set(TARGET_NAME "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/cmTC_${TARGET_NAME}.dir")
++  file(MAKE_DIRECTORY ${TARGET_NAME})
++
++  file(WRITE "${TARGET_NAME}/CheckSectionExists.c" "${ARG_SOURCE}\n")
++
++  string(REGEX MATCHALL "<[A-Za-z0-9_]*>" substitutions
++         ${CMAKE_C_COMPILE_OBJECT})
++
++  set(try_compile_flags "${ARG_FLAGS}")
++  if(CMAKE_C_COMPILER_ID MATCHES Clang AND CMAKE_C_COMPILER_TARGET)
++    list(APPEND try_compile_flags "-target ${CMAKE_C_COMPILER_TARGET}")
++  endif()
++
++  string(REPLACE ";" " " extra_flags "${try_compile_flags}")
++
++  set(test_compile_command "${CMAKE_C_COMPILE_OBJECT}")
++  foreach(substitution ${substitutions})
++    if(substitution STREQUAL "<CMAKE_C_COMPILER>")
++      string(REPLACE "<CMAKE_C_COMPILER>"
++             "${CMAKE_C_COMPILER}" test_compile_command ${test_compile_command})
++    elseif(substitution STREQUAL "<OBJECT>")
++      string(REPLACE "<OBJECT>" "${TARGET_NAME}/CheckSectionExists.o"
++             test_compile_command ${test_compile_command})
++    elseif(substitution STREQUAL "<SOURCE>")
++      string(REPLACE "<SOURCE>" "${TARGET_NAME}/CheckSectionExists.c"
++             test_compile_command ${test_compile_command})
++    elseif(substitution STREQUAL "<FLAGS>")
++      string(REPLACE "<FLAGS>" "${CMAKE_C_FLAGS} ${extra_flags}"
++             test_compile_command ${test_compile_command})
++    else()
++      string(REPLACE "${substitution}" "" test_compile_command
++             ${test_compile_command})
++    endif()
++  endforeach()
++
++  string(REPLACE " " ";" test_compile_command "${test_compile_command}")
++
++  execute_process(
++    COMMAND ${test_compile_command}
++    RESULT_VARIABLE TEST_RESULT
++    OUTPUT_VARIABLE TEST_OUTPUT
++    ERROR_VARIABLE TEST_ERROR
++  )
++
++  execute_process(
++    COMMAND ${CMAKE_OBJDUMP} -h "${TARGET_NAME}/CheckSectionExists.o"
++    RESULT_VARIABLE CHECK_RESULT
++    OUTPUT_VARIABLE CHECK_OUTPUT
++    ERROR_VARIABLE CHECK_ERROR
++  )
++  string(FIND "${CHECK_OUTPUT}" "${section}" SECTION_FOUND)
++
++  if(NOT SECTION_FOUND EQUAL -1)
++    set(${output} TRUE PARENT_SCOPE)
++  else()
++    set(${output} FALSE PARENT_SCOPE)
++  endif()
++
++  file(REMOVE_RECURSE ${TARGET_NAME})
++endfunction()
++
++check_cxx_section_exists(".init_array" COMPILER_RT_HAS_INITFINI_ARRAY
++  SOURCE "__attribute__((constructor)) void f() {}\nint main() { return 0; }\n")
++
++append_list_if(COMPILER_RT_HAS_INITFINI_ARRAY -DCRT_HAS_INITFINI_ARRAY CRT_CFLAGS)
++append_list_if(COMPILER_RT_HAS_FPIC_FLAG -fPIC CRT_CFLAGS)
++
++foreach(arch ${CRT_SUPPORTED_ARCH})
++  add_compiler_rt_runtime(clang_rt.crtbegin
++    OBJECT
++    ARCHS ${arch}
++    SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/crtbegin.c
++    CFLAGS ${CRT_CFLAGS}
++    PARENT_TARGET crt)
++  add_compiler_rt_runtime(clang_rt.crtbegin_shared
++    OBJECT
++    ARCHS ${arch}
++    SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/crtbegin.c
++    CFLAGS ${CRT_CFLAGS} -DCRT_SHARED
++    PARENT_TARGET crt)
++  add_compiler_rt_runtime(clang_rt.crtend
++    OBJECT
++    ARCHS ${arch}
++    SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/crtend.c
++    CFLAGS ${CRT_CFLAGS}
++    PARENT_TARGET crt)
++  add_compiler_rt_runtime(clang_rt.crtend_shared
++    OBJECT
++    ARCHS ${arch}
++    SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/crtend.c
++    CFLAGS ${CRT_CFLAGS} -DCRT_SHARED
++    PARENT_TARGET crt)
++endforeach()
+Index: compiler-rt/lib/crt/crtbegin.c
+===================================================================
+--- /dev/null
++++ compiler-rt/lib/crt/crtbegin.c
+@@ -0,0 +1,108 @@
++/* ===-- crtbegin.c - Start of constructors and destructors ----------------===
++ *
++ *      	       The LLVM Compiler Infrastructure
++ *
++ * This file is dual licensed under the MIT and the University of Illinois Open
++ * Source Licenses. See LICENSE.TXT for details.
++ *
++ * ===----------------------------------------------------------------------===
++ */
++
++#include <stddef.h>
++
++__attribute__((visibility("hidden")))
++#ifdef CRT_SHARED
++void *__dso_handle = &__dso_handle;
++#else
++void *__dso_handle = (void *)0;
++#endif
++
++static long __EH_FRAME_LIST__[]
++    __attribute__((section(".eh_frame"), aligned(sizeof(void *)))) = {};
++
++extern void __register_frame_info(const void *, void *) __attribute__((weak));
++extern void *__deregister_frame_info(const void *) __attribute__((weak));
++
++#ifndef CRT_HAS_INITFINI_ARRAY
++typedef void (*fp)(void);
++
++static fp __CTOR_LIST__[]
++    __attribute__((section(".ctors"), aligned(sizeof(fp)), used)) = {(fp)-1};
++extern fp __CTOR_LIST_END__[];
++#endif
++
++#ifdef CRT_SHARED
++extern void __cxa_finalize(void *) __attribute__((weak));
++#endif
++
++static void __attribute__((used)) __do_init() {
++  static _Bool __initialized;
++  if (__builtin_expect(__initialized, 0))
++    return;
++  __initialized = 1;
++
++  static struct { void *p[8]; } __object;
++  if (__register_frame_info)
++    __register_frame_info(__EH_FRAME_LIST__, &__object);
++
++#ifndef CRT_HAS_INITFINI_ARRAY
++  const size_t n = __CTOR_LIST_END__ - __CTOR_LIST__ - 1;
++  for (size_t i = n; i >= 1; i--) __CTOR_LIST__[i]();
++#endif
++}
++
++#ifdef CRT_HAS_INITFINI_ARRAY
++__attribute__((section(".init_array"),
++               used)) static void (*__init)(void) = __do_init;
++#else  // CRT_HAS_INITFINI_ARRAY
++#if defined(__i386__) || defined(__x86_64__)
++asm(".pushsection .init,\"ax\",@progbits\n\t"
++    "call " __USER_LABEL_PREFIX__ "__do_init\n\t"
++    ".popsection");
++#elif defined(__arm__)
++asm(".pushsection .init,\"ax\",%progbits\n\t"
++    "bl " __USER_LABEL_PREFIX__ "__do_init\n\t"
++    ".popsection");
++#endif  // CRT_HAS_INITFINI_ARRAY
++#endif
++
++#ifndef CRT_HAS_INITFINI_ARRAY
++static fp __DTOR_LIST__[]
++    __attribute__((section(".dtors"), aligned(sizeof(fp)), used)) = {(fp)-1};
++extern fp __DTOR_LIST_END__[];
++#endif
++
++static void __attribute__((used)) __do_fini() {
++  static _Bool __finalized;
++  if (__builtin_expect(__finalized, 0))
++    return;
++  __finalized = 1;
++
++#ifdef CRT_SHARED
++  if (__cxa_finalize)
++    __cxa_finalize(__dso_handle);
++#endif
++
++#ifndef CRT_HAS_INITFINI_ARRAY
++  if (__deregister_frame_info)
++    __deregister_frame_info(__EH_FRAME_LIST__);
++
++  const size_t n = __DTOR_LIST_END__ - __DTOR_LIST__ - 1;
++  for (size_t i = 1; i < n; i++) __DTOR_LIST__[i]();
++#endif
++}
++
++#ifdef CRT_HAS_INITFINI_ARRAY
++__attribute__((section(".fini_array"),
++               used)) static void (*__fini)(void) = __do_fini;
++#else  // CRT_HAS_INITFINI_ARRAY
++#if defined(__i386__) || defined(__x86_64__)
++asm(".pushsection .fini,\"ax\",@progbits\n\t"
++    "call " __USER_LABEL_PREFIX__ "__do_fini\n\t"
++    ".popsection");
++#elif defined(__arm__)
++asm(".pushsection .fini,\"ax\",%progbits\n\t"
++    "bl " __USER_LABEL_PREFIX__ "__do_fini\n\t"
++    ".popsection");
++#endif
++#endif  // CRT_HAS_INIT_FINI_ARRAY
+Index: compiler-rt/lib/crt/crtend.c
+===================================================================
+--- /dev/null
++++ compiler-rt/lib/crt/crtend.c
+@@ -0,0 +1,24 @@
++/* ===-- crtend.c - End of constructors and destructors --------------------===
++ *
++ *      	       The LLVM Compiler Infrastructure
++ *
++ * This file is dual licensed under the MIT and the University of Illinois Open
++ * Source Licenses. See LICENSE.TXT for details.
++ *
++ * ===----------------------------------------------------------------------===
++ */
++
++#include <stdint.h>
++
++// Put 4-byte zero which is the length field in FDE at the end as a terminator.
++const int32_t __EH_FRAME_LIST_END__[]
++    __attribute__((section(".eh_frame"), aligned(sizeof(int32_t)),
++                   visibility("hidden"), used)) = {0};
++
++#ifndef CRT_HAS_INITFINI_ARRAY
++typedef void (*fp)(void);
++fp __CTOR_LIST_END__[]
++    __attribute__((section(".ctors"), visibility("hidden"), used)) = {0};
++fp __DTOR_LIST_END__[]
++    __attribute__((section(".dtors"), visibility("hidden"), used)) = {0};
++#endif
+Index: compiler-rt/test/CMakeLists.txt
+===================================================================
+--- compiler-rt/test/CMakeLists.txt
++++ compiler-rt/test/CMakeLists.txt
+@@ -73,6 +73,9 @@
+   if(COMPILER_RT_BUILD_XRAY)
+     compiler_rt_test_runtime(xray)
+   endif()
++  if(COMPILER_RT_HAS_CRT)
++    add_subdirectory(crt)
++  endif()
+   # ShadowCallStack does not yet provide a runtime with compiler-rt, the tests
+   # include their own minimal runtime
+   add_subdirectory(shadowcallstack)
+Index: compiler-rt/test/crt/CMakeLists.txt
+===================================================================
+--- /dev/null
++++ compiler-rt/test/crt/CMakeLists.txt
+@@ -0,0 +1,31 @@
++set(CRT_LIT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
++
++set(CRT_TESTSUITES)
++
++set(CRT_TEST_DEPS "")
++
++if(NOT COMPILER_RT_STANDALONE_BUILD AND COMPILER_RT_BUILD_CRT AND
++   COMPILER_RT_HAS_CRT)
++  list(APPEND CRT_TEST_DEPS crt)
++endif()
++
++set(CRT_TEST_ARCH ${CRT_SUPPORTED_ARCH})
++if (COMPILER_RT_BUILD_CRT AND COMPILER_RT_HAS_CRT)
++  foreach(arch ${CRT_TEST_ARCH})
++    set(CRT_TEST_TARGET_ARCH ${arch})
++    string(TOLOWER "-${arch}-${OS_NAME}" CRT_TEST_CONFIG_SUFFIX)
++    get_test_cc_for_arch(${arch} CRT_TEST_TARGET_CC CRT_TEST_TARGET_CFLAGS)
++    string(TOUPPER ${arch} ARCH_UPPER_CASE)
++    set(CONFIG_NAME ${ARCH_UPPER_CASE}${OS_NAME}Config)
++
++    configure_lit_site_cfg(
++      ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in
++      ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME}/lit.site.cfg)
++    list(APPEND CRT_TESTSUITES ${CMAKE_CURRENT_BINARY_DIR}/${CONFIG_NAME})
++  endforeach()
++endif()
++
++add_lit_testsuite(check-crt "Running the CRT tests"
++  ${CRT_TESTSUITES}
++  DEPENDS ${CRT_TEST_DEPS})
++set_target_properties(check-crt PROPERTIES FOLDER "Compiler-RT Misc")
+Index: compiler-rt/test/crt/dso_handle.cpp
+===================================================================
+--- /dev/null
++++ compiler-rt/test/crt/dso_handle.cpp
+@@ -0,0 +1,33 @@
++// RUN: %clangxx -g -DCRT_SHARED -c %s -fPIC -o %tshared.o
++// RUN: %clangxx -g -c %s -fPIC -o %t.o
++// RUN: %clangxx -g -shared -o %t.so -nostdlib %crti %shared_crtbegin %tshared.o %libstdcxx -lc -lm -lgcc_s %shared_crtend %crtn
++// RUN: %clangxx -g -o %t -nostdlib %crt1 %crti %crtbegin %t.o %libstdcxx -lc -lm %libgcc %t.so %crtend %crtn
++// RUN: %run %t 2>&1 | FileCheck %s
++
++#include <stdio.h>
++
++// CHECK: 1
++// CHECK-NEXT: ~A()
++
++#ifdef CRT_SHARED
++bool G;
++void C() {
++  printf("%d\n", G);
++}
++
++struct A {
++  A() { G = true; }
++  ~A() {
++    printf("~A()\n");
++  }
++};
++
++A a;
++#else
++void C();
++
++int main() {
++  C();
++  return 0;
++}
++#endif
+Index: compiler-rt/test/crt/lit.cfg
+===================================================================
+--- /dev/null
++++ compiler-rt/test/crt/lit.cfg
+@@ -0,0 +1,80 @@
++# -*- Python -*-
++
++import os
++import subprocess
++
++# Setup config name.
++config.name = 'CRT' + config.name_suffix
++
++# Setup source root.
++config.test_source_root = os.path.dirname(__file__)
++
++
++def get_library_path(file):
++    cmd = subprocess.Popen([config.clang.strip(),
++                            config.target_cflags.strip(),
++                            '-print-file-name=%s' % file],
++                           stdout=subprocess.PIPE,
++                           env=config.environment)
++    if not cmd.stdout:
++      lit_config.fatal("Couldn't find the library path for '%s'" % file)
++    dir = cmd.stdout.read().strip()
++    if sys.platform in ['win32'] and execute_external:
++        # Don't pass dosish path separator to msys bash.exe.
++        dir = dir.replace('\\', '/')
++    # Ensure the result is an ascii string, across Python2.5+ - Python3.
++    return str(dir.decode('ascii'))
++
++
++def get_libgcc_file_name():
++    cmd = subprocess.Popen([config.clang.strip(),
++                            config.target_cflags.strip(),
++                            '-print-libgcc-file-name'],
++                           stdout=subprocess.PIPE,
++                           env=config.environment)
++    if not cmd.stdout:
++      lit_config.fatal("Couldn't find the library path for '%s'" % file)
++    dir = cmd.stdout.read().strip()
++    if sys.platform in ['win32'] and execute_external:
++        # Don't pass dosish path separator to msys bash.exe.
++        dir = dir.replace('\\', '/')
++    # Ensure the result is an ascii string, across Python2.5+ - Python3.
++    return str(dir.decode('ascii'))
++
++
++def build_invocation(compile_flags):
++    return ' ' + ' '.join([config.clang] + compile_flags) + ' '
++
++
++# Setup substitutions.
++config.substitutions.append(
++    ('%clang ', build_invocation([config.target_cflags])))
++config.substitutions.append(
++    ('%clangxx ',
++     build_invocation(config.cxx_mode_flags + [config.target_cflags])))
++
++base_lib = os.path.join(
++    config.compiler_rt_libdir, "clang_rt.%%s-%s.o" % config.target_arch)
++config.substitutions.append(('%crtbegin', base_lib % "crtbegin"))
++config.substitutions.append(('%shared_crtbegin', base_lib % "crtbegin_shared"))
++config.substitutions.append(('%crtend', base_lib % "crtend"))
++config.substitutions.append(('%shared_crtend', base_lib % "crtend_shared"))
++
++config.substitutions.append(
++    ('%crt1', get_library_path('crt1.o')))
++config.substitutions.append(
++    ('%crti', get_library_path('crti.o')))
++config.substitutions.append(
++    ('%crtn', get_library_path('crtn.o')))
++
++config.substitutions.append(
++    ('%libgcc', get_libgcc_file_name()))
++
++config.substitutions.append(
++    ('%libstdcxx', '-l' + config.sanitizer_cxx_lib.lstrip('lib')))
++
++# Default test suffixes.
++config.suffixes = ['.c', '.cc', '.cpp']
++
++if config.host_os not in ['Linux']:
++    config.unsupported = True
+Index: compiler-rt/test/crt/lit.site.cfg.in
+===================================================================
+--- /dev/null
++++ compiler-rt/test/crt/lit.site.cfg.in
+@@ -0,0 +1,14 @@
++@LIT_SITE_CFG_IN_HEADER@
++
++# Tool-specific config options.
++config.name_suffix = "@CRT_TEST_CONFIG_SUFFIX@"
++config.crt_lit_source_dir = "@CRT_LIT_SOURCE_DIR@"
++config.target_cflags = "@CRT_TEST_TARGET_CFLAGS@"
++config.target_arch = "@CRT_TEST_TARGET_ARCH@"
++config.sanitizer_cxx_lib = "@SANITIZER_TEST_CXX_LIBNAME@"
++
++# Load common config for all compiler-rt lit tests
++lit_config.load_config(config, "@COMPILER_RT_BINARY_DIR@/test/lit.common.configured")
++
++# Load tool-specific config that would do the real work.
++lit_config.load_config(config, "@CRT_LIT_SOURCE_DIR@/lit.cfg")
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/default.nix b/nixpkgs/pkgs/development/compilers/llvm/8/default.nix
new file mode 100644
index 000000000000..3503e6b83d2e
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/default.nix
@@ -0,0 +1,193 @@
+{ lowPrio, newScope, pkgs, stdenv, cmake, libstdcxxHook
+, libxml2, python, isl, fetchurl, overrideCC, wrapCCWith, wrapBintoolsWith
+, buildLlvmTools # tools, but from the previous stage, for cross
+, targetLlvmLibraries # libraries, but from the next stage, for cross
+}:
+
+let
+  release_version = "8.0.0";
+  version = release_version; # differentiating these is important for rc's
+
+  fetch = name: sha256: fetchurl {
+    url = "https://releases.llvm.org/${release_version}/${name}-${version}.src.tar.xz";
+    inherit sha256;
+  };
+
+  clang-tools-extra_src = fetch "clang-tools-extra" "0jwx6nnshp92pd5852y7ip7qhaqdf8az5g0440pli9q8whmi402g";
+
+  tools = stdenv.lib.makeExtensible (tools: let
+    callPackage = newScope (tools // { inherit stdenv cmake libxml2 python isl release_version version fetch; });
+    mkExtraBuildCommands = cc: ''
+      rsrc="$out/resource-root"
+      mkdir "$rsrc"
+      ln -s "${cc}/lib/clang/${release_version}/include" "$rsrc"
+      ln -s "${targetLlvmLibraries.compiler-rt.out}/lib" "$rsrc/lib"
+      echo "-resource-dir=$rsrc" >> $out/nix-support/cc-cflags
+    '' + stdenv.lib.optionalString (stdenv.targetPlatform.isLinux && tools.clang-unwrapped ? gcc && !(stdenv.targetPlatform.useLLVM or false)) ''
+      echo "--gcc-toolchain=${tools.clang-unwrapped.gcc}" >> $out/nix-support/cc-cflags
+    '';
+  in {
+
+    llvm = callPackage ./llvm.nix { };
+    llvm-polly = callPackage ./llvm.nix { enablePolly = true; };
+
+    clang-unwrapped = callPackage ./clang {
+      inherit clang-tools-extra_src;
+    };
+    clang-polly-unwrapped = callPackage ./clang {
+      inherit clang-tools-extra_src;
+      llvm = tools.llvm-polly;
+      enablePolly = true;
+    };
+
+    llvm-manpages = lowPrio (tools.llvm.override {
+      enableManpages = true;
+      python = pkgs.python;  # don't use python-boot
+    });
+
+    clang-manpages = lowPrio (tools.clang-unwrapped.override {
+      enableManpages = true;
+      python = pkgs.python;  # don't use python-boot
+    });
+
+    libclang = tools.clang-unwrapped.lib;
+
+    clang = if stdenv.cc.isGNU then tools.libstdcxxClang else tools.libcxxClang;
+
+    libstdcxxClang = wrapCCWith rec {
+      cc = tools.clang-unwrapped;
+      extraPackages = [
+        libstdcxxHook
+        targetLlvmLibraries.compiler-rt
+      ];
+      extraBuildCommands = mkExtraBuildCommands cc;
+    };
+
+    libcxxClang = wrapCCWith rec {
+      cc = tools.clang-unwrapped;
+      libcxx = targetLlvmLibraries.libcxx;
+      extraPackages = [
+        targetLlvmLibraries.libcxx
+        targetLlvmLibraries.libcxxabi
+        targetLlvmLibraries.compiler-rt
+      ];
+      extraBuildCommands = mkExtraBuildCommands cc;
+    };
+
+    lld = callPackage ./lld.nix {};
+
+    lldb = callPackage ./lldb.nix {};
+
+    # Below, is the LLVM bootstrapping logic. It handles building a
+    # fully LLVM toolchain from scratch. No GCC toolchain should be
+    # pulled in. As a consequence, it is very quick to build different
+    # targets provided by LLVM and we can also build for what GCC
+    # doesn’t support like LLVM. Probably we should move to some other
+    # file.
+
+    bintools = callPackage ./bintools.nix {};
+
+    lldClang = wrapCCWith rec {
+      cc = tools.clang-unwrapped;
+      libcxx = targetLlvmLibraries.libcxx;
+      bintools = wrapBintoolsWith {
+        inherit (tools) bintools;
+      };
+      extraPackages = [
+        targetLlvmLibraries.libcxx
+        targetLlvmLibraries.libcxxabi
+        targetLlvmLibraries.compiler-rt
+        targetLlvmLibraries.libunwind
+      ];
+      extraBuildCommands = ''
+        echo "-target ${stdenv.targetPlatform.config}" >> $out/nix-support/cc-cflags
+        echo "-rtlib=compiler-rt -Wno-unused-command-line-argument" >> $out/nix-support/cc-cflags
+        echo "-B${targetLlvmLibraries.compiler-rt}/lib" >> $out/nix-support/cc-cflags
+        echo "--unwindlib=libunwind" >> $out/nix-support/cc-cflags
+      '' + mkExtraBuildCommands cc;
+    };
+
+    lldClangNoLibcxx = wrapCCWith rec {
+      cc = tools.clang-unwrapped;
+      libcxx = null;
+      bintools = wrapBintoolsWith {
+        inherit (tools) bintools;
+      };
+      extraPackages = [
+        targetLlvmLibraries.compiler-rt
+      ];
+      extraBuildCommands = ''
+        echo "-target ${stdenv.targetPlatform.config}" >> $out/nix-support/cc-cflags
+        echo "-rtlib=compiler-rt" >> $out/nix-support/cc-cflags
+        echo "-B${targetLlvmLibraries.compiler-rt}/lib" >> $out/nix-support/cc-cflags
+        echo "-nostdlib++" >> $out/nix-support/cc-cflags
+      '' + mkExtraBuildCommands cc;
+    };
+
+    lldClangNoLibc = wrapCCWith rec {
+      cc = tools.clang-unwrapped;
+      libcxx = null;
+      bintools = wrapBintoolsWith {
+        inherit (tools) bintools;
+        libc = null;
+      };
+      extraPackages = [
+        targetLlvmLibraries.compiler-rt
+      ];
+      extraBuildCommands = ''
+        echo "-target ${stdenv.targetPlatform.config}" >> $out/nix-support/cc-cflags
+        echo "-rtlib=compiler-rt" >> $out/nix-support/cc-cflags
+        echo "-B${targetLlvmLibraries.compiler-rt}/lib" >> $out/nix-support/cc-cflags
+      '' + mkExtraBuildCommands cc;
+    };
+
+    lldClangNoCompilerRt = wrapCCWith rec {
+      cc = tools.clang-unwrapped;
+      libcxx = null;
+      bintools = wrapBintoolsWith {
+        inherit (tools) bintools;
+        libc = null;
+      };
+      extraPackages = [ ];
+      extraBuildCommands = ''
+        echo "-nostartfiles" >> $out/nix-support/cc-cflags
+        echo "-target ${stdenv.targetPlatform.config}" >> $out/nix-support/cc-cflags
+      '';
+    };
+
+  });
+
+  libraries = stdenv.lib.makeExtensible (libraries: let
+    callPackage = newScope (libraries // buildLlvmTools // { inherit stdenv cmake libxml2 python isl release_version version fetch; });
+  in {
+
+    compiler-rt = callPackage ./compiler-rt.nix ({} //
+      (stdenv.lib.optionalAttrs (stdenv.hostPlatform.useLLVM or false) {
+        stdenv = overrideCC stdenv buildLlvmTools.lldClangNoCompilerRt;
+      }));
+
+    stdenv = overrideCC stdenv buildLlvmTools.clang;
+
+    libcxxStdenv = overrideCC stdenv buildLlvmTools.libcxxClang;
+
+    libcxx = callPackage ./libc++ ({} //
+      (stdenv.lib.optionalAttrs (stdenv.hostPlatform.useLLVM or false) {
+        stdenv = overrideCC stdenv buildLlvmTools.lldClangNoLibcxx;
+      }));
+
+    libcxxabi = callPackage ./libc++abi.nix ({} //
+      (stdenv.lib.optionalAttrs (stdenv.hostPlatform.useLLVM or false) {
+        stdenv = overrideCC stdenv buildLlvmTools.lldClangNoLibcxx;
+        libunwind = libraries.libunwind;
+      }));
+
+    openmp = callPackage ./openmp.nix {};
+
+    libunwind = callPackage ./libunwind.nix ({} //
+      (stdenv.lib.optionalAttrs (stdenv.hostPlatform.useLLVM or false) {
+        stdenv = overrideCC stdenv buildLlvmTools.lldClangNoLibcxx;
+      }));
+
+  });
+
+in { inherit tools libraries; } // libraries // tools
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/libc++/default.nix b/nixpkgs/pkgs/development/compilers/llvm/8/libc++/default.nix
new file mode 100644
index 000000000000..d0a5c37c4148
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/libc++/default.nix
@@ -0,0 +1,51 @@
+{ lib, stdenv, fetch, cmake, python, libcxxabi, fixDarwinDylibNames, version }:
+
+stdenv.mkDerivation rec {
+  name = "libc++-${version}";
+
+  src = fetch "libcxx" "1qlx3wlxrnc5cwc1fcfc2vhfsl7j4294hi8y5kxj8hy8wxsjd462";
+
+  postUnpack = ''
+    unpackFile ${libcxxabi.src}
+    export LIBCXXABI_INCLUDE_DIR="$PWD/$(ls -d libcxxabi-${version}*)/include"
+  '';
+
+  patches = stdenv.lib.optional stdenv.hostPlatform.isMusl ../../libcxx-0001-musl-hacks.patch;
+
+  prePatch = ''
+    substituteInPlace lib/CMakeLists.txt --replace "/usr/lib/libc++" "\''${LIBCXX_LIBCXXABI_LIB_PATH}/libc++"
+  '';
+
+  preConfigure = ''
+    # Get headers from the cxxabi source so we can see private headers not installed by the cxxabi package
+    cmakeFlagsArray=($cmakeFlagsArray -DLIBCXX_CXX_ABI_INCLUDE_PATHS="$LIBCXXABI_INCLUDE_DIR")
+  '' + lib.optionalString stdenv.hostPlatform.isMusl ''
+    patchShebangs utils/cat_files.py
+  '';
+  nativeBuildInputs = [ cmake ] ++ stdenv.lib.optional stdenv.hostPlatform.isMusl python;
+
+  buildInputs = [ libcxxabi ] ++ lib.optional stdenv.isDarwin fixDarwinDylibNames;
+
+  cmakeFlags = [
+    "-DLIBCXX_LIBCXXABI_LIB_PATH=${libcxxabi}/lib"
+    "-DLIBCXX_LIBCPPABI_VERSION=2"
+    "-DLIBCXX_CXX_ABI=libcxxabi"
+  ] ++ stdenv.lib.optional stdenv.hostPlatform.isMusl "-DLIBCXX_HAS_MUSL_LIBC=1"
+    ++ stdenv.lib.optional (stdenv.hostPlatform.useLLVM or false) "-DLIBCXX_USE_COMPILER_RT=ON";
+
+  enableParallelBuilding = true;
+
+  linkCxxAbi = stdenv.isLinux;
+
+  setupHooks = [
+    ../../../../../build-support/setup-hooks/role.bash
+    ./setup-hook.sh
+  ];
+
+  meta = {
+    homepage = http://libcxx.llvm.org/;
+    description = "A new implementation of the C++ standard library, targeting C++11";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/libc++/setup-hook.sh b/nixpkgs/pkgs/development/compilers/llvm/8/libc++/setup-hook.sh
new file mode 100644
index 000000000000..6611259165ae
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/libc++/setup-hook.sh
@@ -0,0 +1,6 @@
+# See pkgs/build-support/setup-hooks/role.bash
+getHostRole
+
+linkCxxAbi="@linkCxxAbi@"
+export NIX_${role_pre}CXXSTDLIB_COMPILE+=" -isystem @out@/include/c++/v1"
+export NIX_${role_pre}CXXSTDLIB_LINK=" -stdlib=libc++${linkCxxAbi:+" -lc++abi"}"
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/libc++abi.nix b/nixpkgs/pkgs/development/compilers/llvm/8/libc++abi.nix
new file mode 100644
index 000000000000..0eb5ebca5159
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/libc++abi.nix
@@ -0,0 +1,55 @@
+{ stdenv, cmake, fetch, libcxx, libunwind, llvm, version }:
+
+stdenv.mkDerivation {
+  name = "libc++abi-${version}";
+
+  src = fetch "libcxxabi" "1k875f977ybdkpdnr9105wa6hccy9qvpd9xd42n75h7p56bdxmn2";
+
+  nativeBuildInputs = [ cmake ];
+  buildInputs = stdenv.lib.optional (!stdenv.isDarwin && !stdenv.isFreeBSD) libunwind;
+
+  cmakeFlags = stdenv.lib.optionals (stdenv.hostPlatform.useLLVM or false) [
+    "-DLLVM_ENABLE_LIBCXX=ON"
+    "-DLIBCXXABI_USE_LLVM_UNWINDER=ON"
+  ];
+
+  postUnpack = ''
+    unpackFile ${libcxx.src}
+    unpackFile ${llvm.src}
+    cmakeFlags+=" -DLLVM_PATH=$PWD/$(ls -d llvm-*) -DLIBCXXABI_LIBCXX_PATH=$PWD/$(ls -d libcxx-*)"
+  '' + stdenv.lib.optionalString stdenv.isDarwin ''
+    export TRIPLE=x86_64-apple-darwin
+  '' + stdenv.lib.optionalString stdenv.hostPlatform.isMusl ''
+    patch -p1 -d $(ls -d libcxx-*) -i ${../libcxx-0001-musl-hacks.patch}
+  '';
+
+  installPhase = if stdenv.isDarwin
+    then ''
+      for file in lib/*.dylib; do
+        # this should be done in CMake, but having trouble figuring out
+        # the magic combination of necessary CMake variables
+        # if you fancy a try, take a look at
+        # http://www.cmake.org/Wiki/CMake_RPATH_handling
+        install_name_tool -id $out/$file $file
+      done
+      make install
+      install -d 755 $out/include
+      install -m 644 ../include/*.h $out/include
+    ''
+    else ''
+      install -d -m 755 $out/include $out/lib
+      install -m 644 lib/libc++abi.a $out/lib
+      install -m 644 lib/libc++abi.so.1.0 $out/lib
+      install -m 644 ../include/cxxabi.h $out/include
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so
+      ln -s libc++abi.so.1.0 $out/lib/libc++abi.so.1
+    '';
+
+  meta = {
+    homepage = http://libcxxabi.llvm.org/;
+    description = "A new implementation of low level support for a standard C++ library";
+    license = with stdenv.lib.licenses; [ ncsa mit ];
+    maintainers = with stdenv.lib.maintainers; [ vlstill ];
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/libunwind.nix b/nixpkgs/pkgs/development/compilers/llvm/8/libunwind.nix
new file mode 100644
index 000000000000..a187d0adc994
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/libunwind.nix
@@ -0,0 +1,22 @@
+{ stdenv, version, fetch, cmake, libcxx, fetchpatch }:
+
+stdenv.mkDerivation {
+  name = "libunwind-${version}";
+
+  src = fetch "libunwind" "0q7ndlldid9wchnny0a936llwxj7zgb9gxp46wjjxvwwkik3l97z";
+
+  nativeBuildInputs = [ cmake ];
+
+  patches = [
+    (fetchpatch {
+      url = "https://github.com/llvm-mirror/libunwind/commit/34a45c630d4c79af403661d267db42fbe7de1178.patch";
+      sha256 = "0n0pv6jvcky8pn3srhrf9x5kbnd0d2kia9xlx2g590f5q0bgwfhv";
+    })
+    (fetchpatch {
+      url = "https://github.com/llvm-mirror/libunwind/commit/e050272d2eb57eb4e56a37b429a61df2ebb8aa3e.patch";
+      sha256 = "1sxyx5xnax8k713jjcxgq3jq3cpnxygs2rcdf5vfja0f2k9jzldl";
+    })
+  ];
+
+  enableParallelBuilding = true;
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/lld.nix b/nixpkgs/pkgs/development/compilers/llvm/8/lld.nix
new file mode 100644
index 000000000000..7fff6843c5f4
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/lld.nix
@@ -0,0 +1,32 @@
+{ stdenv
+, fetch
+, cmake
+, libxml2
+, llvm
+, version
+}:
+
+stdenv.mkDerivation {
+  name = "lld-${version}";
+
+  src = fetch "lld" "0dvf38pbm7jy88g66mz7ikkdfhm2qpj0iyzh62hzycifjbnciblw";
+
+  nativeBuildInputs = [ cmake ];
+  buildInputs = [ llvm libxml2 ];
+
+  outputs = [ "out" "dev" ];
+
+  enableParallelBuilding = true;
+
+  postInstall = ''
+    moveToOutput include "$dev"
+    moveToOutput lib "$dev"
+  '';
+
+  meta = {
+    description = "The LLVM Linker";
+    homepage    = http://lld.llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/lldb.nix b/nixpkgs/pkgs/development/compilers/llvm/8/lldb.nix
new file mode 100644
index 000000000000..ae9198e99d27
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/lldb.nix
@@ -0,0 +1,60 @@
+{ stdenv
+, fetch
+, cmake
+, zlib
+, ncurses
+, swig
+, which
+, libedit
+, libxml2
+, llvm
+, clang-unwrapped
+, python
+, version
+, darwin
+}:
+
+stdenv.mkDerivation {
+  name = "lldb-${version}";
+
+  src = fetch "lldb" "0wq3mi76fk86g2g2bcsr0yhagh1dlf2myk641ai58rc116gqp4a9";
+
+  postPatch = ''
+    # Fix up various paths that assume llvm and clang are installed in the same place
+    sed -i 's,".*ClangConfig.cmake","${clang-unwrapped}/lib/cmake/clang/ClangConfig.cmake",' \
+      cmake/modules/LLDBStandalone.cmake
+    sed -i 's,".*tools/clang/include","${clang-unwrapped}/include",' \
+      cmake/modules/LLDBStandalone.cmake
+    sed -i 's,"$.LLVM_LIBRARY_DIR.",${llvm}/lib ${clang-unwrapped}/lib,' \
+      cmake/modules/LLDBStandalone.cmake
+  '';
+
+  nativeBuildInputs = [ cmake python which swig ];
+  buildInputs = [ ncurses zlib libedit libxml2 llvm ]
+    ++ stdenv.lib.optionals stdenv.isDarwin [ darwin.libobjc darwin.apple_sdk.libs.xpc darwin.apple_sdk.frameworks.Foundation darwin.bootstrap_cmds darwin.apple_sdk.frameworks.Carbon darwin.apple_sdk.frameworks.Cocoa darwin.cf-private ];
+
+  CXXFLAGS = "-fno-rtti";
+  hardeningDisable = [ "format" ];
+
+  cmakeFlags = [
+    "-DLLDB_CODESIGN_IDENTITY=" # codesigning makes nondeterministic
+  ];
+
+  enableParallelBuilding = true;
+
+  postInstall = ''
+    mkdir -p $out/share/man/man1
+    cp ../docs/lldb.1 $out/share/man/man1/
+
+    install -D ../tools/lldb-vscode/package.json $out/share/vscode/extensions/llvm-org.lldb-vscode-0.1.0/package.json
+    mkdir $out/share/vscode/extensions/llvm-org.lldb-vscode-0.1.0/bin
+    ln -s $out/bin/lldb-vscode $out/share/vscode/extensions/llvm-org.lldb-vscode-0.1.0/bin
+  '';
+
+  meta = with stdenv.lib; {
+    description = "A next-generation high-performance debugger";
+    homepage    = http://llvm.org/;
+    license     = licenses.ncsa;
+    platforms   = platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/llvm-outputs.patch b/nixpkgs/pkgs/development/compilers/llvm/8/llvm-outputs.patch
new file mode 100644
index 000000000000..40096fa3497f
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/llvm-outputs.patch
@@ -0,0 +1,26 @@
+diff --git a/tools/llvm-config/llvm-config.cpp b/tools/llvm-config/llvm-config.cpp
+index 94d426b..37f7794 100644
+--- a/tools/llvm-config/llvm-config.cpp
++++ b/tools/llvm-config/llvm-config.cpp
+@@ -333,6 +333,21 @@ int main(int argc, char **argv) {
+     ActiveIncludeOption = "-I" + ActiveIncludeDir;
+   }
+ 
++  /// Nix-specific multiple-output handling: override ActiveLibDir if --link-shared
++  if (!IsInDevelopmentTree) {
++    bool WantShared = true;
++    for (int i = 1; i < argc; ++i) {
++      StringRef Arg = argv[i];
++      if (Arg == "--link-shared")
++        WantShared = true;
++      else if (Arg == "--link-static")
++        WantShared = false; // the last one wins
++    }
++
++    if (WantShared)
++      ActiveLibDir = std::string("@lib@") + "/lib" + LLVM_LIBDIR_SUFFIX;
++  }
++
+   /// We only use `shared library` mode in cases where the static library form
+   /// of the components provided are not available; note however that this is
+   /// skipped if we're run from within the build dir. However, once installed,
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/llvm.nix b/nixpkgs/pkgs/development/compilers/llvm/8/llvm.nix
new file mode 100644
index 000000000000..5d8d08167298
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/llvm.nix
@@ -0,0 +1,174 @@
+{ stdenv
+, fetch
+, fetchpatch
+, cmake
+, python
+, libffi
+, libbfd
+, libpfm
+, libxml2
+, ncurses
+, version
+, release_version
+, zlib
+, buildPackages
+, debugVersion ? false
+, enableManpages ? false
+, enableSharedLibraries ? true
+, enablePFM ? !stdenv.isDarwin
+, enablePolly ? false
+}:
+
+let
+  inherit (stdenv.lib) optional optionals optionalString;
+
+  src = fetch "llvm" "0k124sxkfhfi1rca6kzkdraf4axhx99x3cw2rk55056628dvwwl8";
+  polly_src = fetch "polly" "1x4xv3j226rqdddp7b61d71wsx2b8vmmri02ycx27y2fg7ba7xg3";
+
+  # Used when creating a version-suffixed symlink of libLLVM.dylib
+  shortVersion = with stdenv.lib;
+    concatStringsSep "." (take 1 (splitString "." release_version));
+
+in stdenv.mkDerivation (rec {
+  name = "llvm-${version}";
+
+  unpackPhase = ''
+    unpackFile ${src}
+    mv llvm-${version}* llvm
+    sourceRoot=$PWD/llvm
+  '' + optionalString enablePolly ''
+    unpackFile ${polly_src}
+    mv polly-* $sourceRoot/tools/polly
+  '';
+
+  outputs = [ "out" "python" ]
+    ++ optional enableSharedLibraries "lib";
+
+  nativeBuildInputs = [ cmake python ]
+    ++ optionals enableManpages [ python.pkgs.sphinx python.pkgs.recommonmark ];
+
+  buildInputs = [ libxml2 libffi ]
+    ++ optional enablePFM libpfm; # exegesis
+
+  propagatedBuildInputs = [ ncurses zlib ];
+
+  postPatch = optionalString stdenv.isDarwin ''
+    substituteInPlace cmake/modules/AddLLVM.cmake \
+      --replace 'set(_install_name_dir INSTALL_NAME_DIR "@rpath")' "set(_install_name_dir)" \
+      --replace 'set(_install_rpath "@loader_path/../lib" ''${extra_libdir})' ""
+  ''
+  # Patch llvm-config to return correct library path based on --link-{shared,static}.
+  + optionalString (enableSharedLibraries) ''
+    substitute '${./llvm-outputs.patch}' ./llvm-outputs.patch --subst-var lib
+    patch -p1 < ./llvm-outputs.patch
+  '' + ''
+    # FileSystem permissions tests fail with various special bits
+    substituteInPlace unittests/Support/CMakeLists.txt \
+      --replace "Path.cpp" ""
+    rm unittests/Support/Path.cpp
+  '' + optionalString stdenv.hostPlatform.isMusl ''
+    patch -p1 -i ${../TLI-musl.patch}
+    substituteInPlace unittests/Support/CMakeLists.txt \
+      --replace "add_subdirectory(DynamicLibrary)" ""
+    rm unittests/Support/DynamicLibrary/DynamicLibraryTest.cpp
+    # valgrind unhappy with musl or glibc, but fails w/musl only
+    rm test/CodeGen/AArch64/wineh4.mir
+  '' + ''
+    patchShebangs test/BugPoint/compile-custom.ll.py
+  '';
+
+  # hacky fix: created binaries need to be run before installation
+  preBuild = ''
+    mkdir -p $out/
+    ln -sv $PWD/lib $out
+  '';
+
+  cmakeFlags = with stdenv; [
+    "-DCMAKE_BUILD_TYPE=${if debugVersion then "Debug" else "Release"}"
+    "-DLLVM_INSTALL_UTILS=ON"  # Needed by rustc
+    "-DLLVM_BUILD_TESTS=ON"
+    "-DLLVM_ENABLE_FFI=ON"
+    "-DLLVM_ENABLE_RTTI=ON"
+    "-DLLVM_HOST_TRIPLE=${stdenv.hostPlatform.config}"
+    "-DLLVM_DEFAULT_TARGET_TRIPLE=${stdenv.hostPlatform.config}"
+    "-DLLVM_ENABLE_DUMP=ON"
+  ] ++ optionals enableSharedLibraries [
+    "-DLLVM_LINK_LLVM_DYLIB=ON"
+  ] ++ optionals enableManpages [
+    "-DLLVM_BUILD_DOCS=ON"
+    "-DLLVM_ENABLE_SPHINX=ON"
+    "-DSPHINX_OUTPUT_MAN=ON"
+    "-DSPHINX_OUTPUT_HTML=OFF"
+    "-DSPHINX_WARNINGS_AS_ERRORS=OFF"
+  ] ++ optionals (!isDarwin) [
+    "-DLLVM_BINUTILS_INCDIR=${libbfd.dev}/include"
+  ] ++ optionals (isDarwin) [
+    "-DLLVM_ENABLE_LIBCXX=ON"
+    "-DCAN_TARGET_i386=false"
+  ] ++ optionals (stdenv.hostPlatform != stdenv.buildPlatform) [
+    "-DCMAKE_CROSSCOMPILING=True"
+    "-DLLVM_TABLEGEN=${buildPackages.llvm_7}/bin/llvm-tblgen"
+  ];
+
+  postBuild = ''
+    rm -fR $out
+  '';
+
+  preCheck = ''
+    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PWD/lib
+  '';
+
+  postInstall = ''
+    mkdir -p $python/share
+    mv $out/share/opt-viewer $python/share/opt-viewer
+  ''
+  + optionalString enableSharedLibraries ''
+    moveToOutput "lib/libLLVM-*" "$lib"
+    moveToOutput "lib/libLLVM${stdenv.hostPlatform.extensions.sharedLibrary}" "$lib"
+    substituteInPlace "$out/lib/cmake/llvm/LLVMExports-${if debugVersion then "debug" else "release"}.cmake" \
+      --replace "\''${_IMPORT_PREFIX}/lib/libLLVM-" "$lib/lib/libLLVM-"
+  ''
+  + optionalString (stdenv.isDarwin && enableSharedLibraries) ''
+    substituteInPlace "$out/lib/cmake/llvm/LLVMExports-${if debugVersion then "debug" else "release"}.cmake" \
+      --replace "\''${_IMPORT_PREFIX}/lib/libLLVM.dylib" "$lib/lib/libLLVM.dylib"
+    ln -s $lib/lib/libLLVM.dylib $lib/lib/libLLVM-${shortVersion}.dylib
+    ln -s $lib/lib/libLLVM.dylib $lib/lib/libLLVM-${release_version}.dylib
+  '';
+
+  doCheck = stdenv.isLinux && (!stdenv.isx86_32);
+
+  checkTarget = "check-all";
+
+  enableParallelBuilding = true;
+
+  passthru.src = src;
+
+  meta = {
+    description = "Collection of modular and reusable compiler and toolchain technologies";
+    homepage    = http://llvm.org/;
+    license     = stdenv.lib.licenses.ncsa;
+    maintainers = with stdenv.lib.maintainers; [ lovek323 raskin dtzWill ];
+    platforms   = stdenv.lib.platforms.all;
+  };
+} // stdenv.lib.optionalAttrs enableManpages {
+  name = "llvm-manpages-${version}";
+
+  buildPhase = ''
+    make docs-llvm-man
+  '';
+
+  propagatedBuildInputs = [];
+
+  installPhase = ''
+    make -C docs install
+  '';
+
+  postPatch = null;
+  postInstall = null;
+
+  outputs = [ "out" ];
+
+  doCheck = false;
+
+  meta.description = "man pages for LLVM ${version}";
+})
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/openmp.nix b/nixpkgs/pkgs/development/compilers/llvm/8/openmp.nix
new file mode 100644
index 000000000000..bf85cae5abe7
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/openmp.nix
@@ -0,0 +1,25 @@
+{ stdenv
+, fetch
+, cmake
+, llvm
+, perl
+, version
+}:
+
+stdenv.mkDerivation {
+  name = "openmp-${version}";
+
+  src = fetch "openmp" "1mf9cpgvix34xlpv0inkgl3qmdvgvp96f7sksqizri0n5xfp1cgp";
+
+  nativeBuildInputs = [ cmake perl ];
+  buildInputs = [ llvm ];
+
+  enableParallelBuilding = true;
+
+  meta = {
+    description = "Components required to build an executable OpenMP program";
+    homepage    = http://openmp.llvm.org/;
+    license     = stdenv.lib.licenses.mit;
+    platforms   = stdenv.lib.platforms.all;
+  };
+}
diff --git a/nixpkgs/pkgs/development/compilers/llvm/8/sanitizers-nongnu.patch b/nixpkgs/pkgs/development/compilers/llvm/8/sanitizers-nongnu.patch
new file mode 100644
index 000000000000..1f2ac97818eb
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/8/sanitizers-nongnu.patch
@@ -0,0 +1,412 @@
+From f7a253f8f85d0f49df6b73996737a3e84ac64236 Mon Sep 17 00:00:00 2001
+From: Will Dietz <w@wdtz.org>
+Date: Mon, 24 Sep 2018 11:17:25 -0500
+Subject: [PATCH] Ported to 7.0, taken from gentoo-musl project.
+
+------
+Ported to compiler-rt-sanitizers-5.0.0. Taken from
+
+https://gist.githubusercontent.com/pwaller/2337f3290f12634cad3e3730cff0a6c1/raw/83c87a8585e2f9662494db5662e5361beb093c26/nongnu.patch
+Signed-off-by: Jory A. Pratt <anarchy@gentoo.org>
+
+Taken from gentoo-musl project, with a few additional minor fixes.
+---
+ lib/asan/asan_linux.cc                        |  4 +-
+ lib/interception/interception_linux.cc        |  2 +-
+ lib/interception/interception_linux.h         |  2 +-
+ lib/msan/msan_linux.cc                        |  2 +-
+ lib/sanitizer_common/sanitizer_allocator.cc   |  2 +-
+ .../sanitizer_common_interceptors_ioctl.inc   |  4 +-
+ .../sanitizer_common_syscalls.inc             |  2 +-
+ lib/sanitizer_common/sanitizer_linux.cc       |  8 +++-
+ .../sanitizer_linux_libcdep.cc                | 10 ++---
+ lib/sanitizer_common/sanitizer_platform.h     |  6 +++
+ .../sanitizer_platform_interceptors.h         |  4 +-
+ .../sanitizer_platform_limits_posix.cc        | 37 +++++++++++--------
+ lib/tsan/rtl/tsan_platform_linux.cc           |  2 +-
+ 13 files changed, 51 insertions(+), 34 deletions(-)
+
+diff --git a/lib/asan/asan_linux.cc b/lib/asan/asan_linux.cc
+index 625f32d40..73cf77aca 100644
+--- a/lib/asan/asan_linux.cc
++++ b/lib/asan/asan_linux.cc
+@@ -46,7 +46,7 @@
+ #include <link.h>
+ #endif
+ 
+-#if SANITIZER_ANDROID || SANITIZER_FREEBSD || SANITIZER_SOLARIS
++#if SANITIZER_ANDROID || SANITIZER_FREEBSD || SANITIZER_SOLARIS || SANITIZER_NONGNU
+ #include <ucontext.h>
+ extern "C" void* _DYNAMIC;
+ #elif SANITIZER_NETBSD
+@@ -139,7 +139,7 @@ void AsanApplyToGlobals(globals_op_fptr op, const void *needle) {
+   UNIMPLEMENTED();
+ }
+ 
+-#if SANITIZER_ANDROID
++#if SANITIZER_ANDROID || SANITIZER_NONGNU
+ // FIXME: should we do anything for Android?
+ void AsanCheckDynamicRTPrereqs() {}
+ void AsanCheckIncompatibleRT() {}
+diff --git a/lib/interception/interception_linux.cc b/lib/interception/interception_linux.cc
+index 26bfcd8f6..529b234f7 100644
+--- a/lib/interception/interception_linux.cc
++++ b/lib/interception/interception_linux.cc
+@@ -43,7 +43,7 @@ bool GetRealFunctionAddress(const char *func_name, uptr *func_addr,
+ }
+ 
+ // Android and Solaris do not have dlvsym
+-#if !SANITIZER_ANDROID && !SANITIZER_SOLARIS && !SANITIZER_OPENBSD
++#if !SANITIZER_ANDROID && !SANITIZER_SOLARIS && !SANITIZER_OPENBSD && !SANITIZER_NONGNU
+ void *GetFuncAddrVer(const char *func_name, const char *ver) {
+   return dlvsym(RTLD_NEXT, func_name, ver);
+ }
+diff --git a/lib/interception/interception_linux.h b/lib/interception/interception_linux.h
+index 942c25609..24a4d5080 100644
+--- a/lib/interception/interception_linux.h
++++ b/lib/interception/interception_linux.h
+@@ -36,7 +36,7 @@ void *GetFuncAddrVer(const char *func_name, const char *ver);
+       (::__interception::uptr) & WRAP(func))
+ 
+ // Android,  Solaris and OpenBSD do not have dlvsym
+-#if !SANITIZER_ANDROID && !SANITIZER_SOLARIS && !SANITIZER_OPENBSD
++#if !SANITIZER_ANDROID && !SANITIZER_SOLARIS && !SANITIZER_OPENBSD && !SANITIZER_NONGNU
+ #define INTERCEPT_FUNCTION_VER_LINUX_OR_FREEBSD(func, symver) \
+   (::__interception::real_##func = (func##_f)(                \
+        unsigned long)::__interception::GetFuncAddrVer(#func, symver))
+diff --git a/lib/msan/msan_linux.cc b/lib/msan/msan_linux.cc
+index 385a650c4..6e30a8ce9 100644
+--- a/lib/msan/msan_linux.cc
++++ b/lib/msan/msan_linux.cc
+@@ -13,7 +13,7 @@
+ //===----------------------------------------------------------------------===//
+ 
+ #include "sanitizer_common/sanitizer_platform.h"
+-#if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD
++#if SANITIZER_FREEBSD || (SANITIZER_LINUX && !SANITIZER_NONGNU) || SANITIZER_NETBSD
+ 
+ #include "msan.h"
+ #include "msan_report.h"
+diff --git a/lib/sanitizer_common/sanitizer_allocator.cc b/lib/sanitizer_common/sanitizer_allocator.cc
+index 6bfd5e5ee..048f6154f 100644
+--- a/lib/sanitizer_common/sanitizer_allocator.cc
++++ b/lib/sanitizer_common/sanitizer_allocator.cc
+@@ -27,7 +27,7 @@ const char *SecondaryAllocatorName = "LargeMmapAllocator";
+ 
+ // ThreadSanitizer for Go uses libc malloc/free.
+ #if SANITIZER_GO || defined(SANITIZER_USE_MALLOC)
+-# if SANITIZER_LINUX && !SANITIZER_ANDROID
++# if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ extern "C" void *__libc_malloc(uptr size);
+ #  if !SANITIZER_GO
+ extern "C" void *__libc_memalign(uptr alignment, uptr size);
+diff --git a/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc b/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
+index 2d633c173..b6eb23116 100644
+--- a/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
++++ b/lib/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
+@@ -104,7 +104,7 @@ static void ioctl_table_fill() {
+   _(SIOCGETVIFCNT, WRITE, struct_sioc_vif_req_sz);
+ #endif
+ 
+-#if SANITIZER_LINUX
++#if SANITIZER_LINUX && !SANITIZER_NONGNU
+   // Conflicting request ids.
+   // _(CDROMAUDIOBUFSIZ, NONE, 0);
+   // _(SNDCTL_TMR_CONTINUE, NONE, 0);
+@@ -365,7 +365,7 @@ static void ioctl_table_fill() {
+   _(VT_WAITACTIVE, NONE, 0);
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   // _(SIOCDEVPLIP, WRITE, struct_ifreq_sz); // the same as EQL_ENSLAVE
+   _(CYGETDEFTHRESH, WRITE, sizeof(int));
+   _(CYGETDEFTIMEOUT, WRITE, sizeof(int));
+diff --git a/lib/sanitizer_common/sanitizer_common_syscalls.inc b/lib/sanitizer_common/sanitizer_common_syscalls.inc
+index 469c8eb7e..24f87867d 100644
+--- a/lib/sanitizer_common/sanitizer_common_syscalls.inc
++++ b/lib/sanitizer_common/sanitizer_common_syscalls.inc
+@@ -2038,7 +2038,7 @@ POST_SYSCALL(setrlimit)(long res, long resource, void *rlim) {
+   }
+ }
+ 
+-#if !SANITIZER_ANDROID
++#if !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ PRE_SYSCALL(prlimit64)(long pid, long resource, const void *new_rlim,
+                        void *old_rlim) {
+   if (new_rlim) PRE_READ(new_rlim, struct_rlimit64_sz);
+diff --git a/lib/sanitizer_common/sanitizer_linux.cc b/lib/sanitizer_common/sanitizer_linux.cc
+index 96d6c1eff..9e2b7fb9d 100644
+--- a/lib/sanitizer_common/sanitizer_linux.cc
++++ b/lib/sanitizer_common/sanitizer_linux.cc
+@@ -541,13 +541,13 @@ const char *GetEnv(const char *name) {
+ #endif
+ }
+ 
+-#if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_OPENBSD
++#if !SANITIZER_FREEBSD && !SANITIZER_NETBSD && !SANITIZER_OPENBSD && !SANITIZER_NONGNU
+ extern "C" {
+ SANITIZER_WEAK_ATTRIBUTE extern void *__libc_stack_end;
+ }
+ #endif
+ 
+-#if !SANITIZER_GO && !SANITIZER_FREEBSD && !SANITIZER_NETBSD &&                \
++#if (!SANITIZER_GO || SANITIZER_NONGNU) && !SANITIZER_FREEBSD && !SANITIZER_NETBSD &&                \
+     !SANITIZER_OPENBSD
+ static void ReadNullSepFileToArray(const char *path, char ***arr,
+                                    int arr_size) {
+@@ -590,6 +590,10 @@ static void GetArgsAndEnv(char ***argv, char ***envp) {
+ #elif SANITIZER_NETBSD
+   *argv = __ps_strings->ps_argvstr;
+   *envp = __ps_strings->ps_envstr;
++#elif SANITIZER_NONGNU
++    static const int kMaxArgv = 2000, kMaxEnvp = 2000;
++    ReadNullSepFileToArray("/proc/self/cmdline", argv, kMaxArgv);
++    ReadNullSepFileToArray("/proc/self/environ", envp, kMaxEnvp);
+ #else // SANITIZER_FREEBSD
+ #if !SANITIZER_GO
+   if (&__libc_stack_end) {
+diff --git a/lib/sanitizer_common/sanitizer_linux_libcdep.cc b/lib/sanitizer_common/sanitizer_linux_libcdep.cc
+index 4962ff832..438f94dbe 100644
+--- a/lib/sanitizer_common/sanitizer_linux_libcdep.cc
++++ b/lib/sanitizer_common/sanitizer_linux_libcdep.cc
+@@ -179,7 +179,7 @@ __attribute__((unused)) static bool GetLibcVersion(int *major, int *minor,
+ }
+ 
+ #if !SANITIZER_FREEBSD && !SANITIZER_ANDROID && !SANITIZER_GO &&               \
+-    !SANITIZER_NETBSD && !SANITIZER_OPENBSD && !SANITIZER_SOLARIS
++    !SANITIZER_NETBSD && !SANITIZER_OPENBSD && !SANITIZER_SOLARIS && !SANITIZER_NONGNU
+ static uptr g_tls_size;
+ 
+ #ifdef __i386__
+@@ -261,7 +261,7 @@ void InitTlsSize() { }
+ #if (defined(__x86_64__) || defined(__i386__) || defined(__mips__) ||          \
+      defined(__aarch64__) || defined(__powerpc64__) || defined(__s390__) ||    \
+      defined(__arm__)) &&                                                      \
+-    SANITIZER_LINUX && !SANITIZER_ANDROID
++    SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ // sizeof(struct pthread) from glibc.
+ static atomic_uintptr_t thread_descriptor_size;
+ 
+@@ -426,7 +426,7 @@ int GetSizeFromHdr(struct dl_phdr_info *info, size_t size, void *data) {
+ 
+ #if !SANITIZER_GO
+ static void GetTls(uptr *addr, uptr *size) {
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ # if defined(__x86_64__) || defined(__i386__) || defined(__s390__)
+   *addr = ThreadSelf();
+   *size = GetTlsSize();
+@@ -470,7 +470,7 @@ static void GetTls(uptr *addr, uptr *size) {
+ #elif SANITIZER_OPENBSD
+   *addr = 0;
+   *size = 0;
+-#elif SANITIZER_ANDROID
++#elif SANITIZER_ANDROID || SANITIZER_NONGNU
+   *addr = 0;
+   *size = 0;
+ #elif SANITIZER_SOLARIS
+@@ -486,7 +486,7 @@ static void GetTls(uptr *addr, uptr *size) {
+ #if !SANITIZER_GO
+ uptr GetTlsSize() {
+ #if SANITIZER_FREEBSD || SANITIZER_ANDROID || SANITIZER_NETBSD ||              \
+-    SANITIZER_OPENBSD || SANITIZER_SOLARIS
++    SANITIZER_OPENBSD || SANITIZER_SOLARIS || SANITIZER_NONGNU
+   uptr addr, size;
+   GetTls(&addr, &size);
+   return size;
+diff --git a/lib/sanitizer_common/sanitizer_platform.h b/lib/sanitizer_common/sanitizer_platform.h
+index d81e25580..e10680ac8 100644
+--- a/lib/sanitizer_common/sanitizer_platform.h
++++ b/lib/sanitizer_common/sanitizer_platform.h
+@@ -208,6 +208,12 @@
+ # define SANITIZER_SOLARIS32 0
+ #endif
+ 
++#if defined(__linux__) && !defined(__GLIBC__)
++# define SANITIZER_NONGNU 1
++#else
++# define SANITIZER_NONGNU 0
++#endif
++
+ #if defined(__myriad2__)
+ # define SANITIZER_MYRIAD2 1
+ #else
+diff --git a/lib/sanitizer_common/sanitizer_platform_interceptors.h b/lib/sanitizer_common/sanitizer_platform_interceptors.h
+index f95539a73..6c53b3415 100644
+--- a/lib/sanitizer_common/sanitizer_platform_interceptors.h
++++ b/lib/sanitizer_common/sanitizer_platform_interceptors.h
+@@ -39,7 +39,7 @@
+ # include "sanitizer_platform_limits_solaris.h"
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ # define SI_LINUX_NOT_ANDROID 1
+ #else
+ # define SI_LINUX_NOT_ANDROID 0
+@@ -322,7 +322,7 @@
+ #define SANITIZER_INTERCEPT_ETHER_R (SI_FREEBSD || SI_LINUX_NOT_ANDROID)
+ #define SANITIZER_INTERCEPT_SHMCTL          \
+   (SI_NETBSD || SI_OPENBSD || SI_SOLARIS || \
+-  ((SI_FREEBSD || SI_LINUX_NOT_ANDROID) && \
++  ((SI_FREEBSD || SI_LINUX_NOT_ANDROID || SANITIZER_NONGNU) && \
+     SANITIZER_WORDSIZE == 64))  // NOLINT
+ #define SANITIZER_INTERCEPT_RANDOM_R SI_LINUX_NOT_ANDROID
+ #define SANITIZER_INTERCEPT_PTHREAD_ATTR_GET SI_POSIX
+diff --git a/lib/sanitizer_common/sanitizer_platform_limits_posix.cc b/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
+index 54da635d7..2f6ff69c3 100644
+--- a/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
++++ b/lib/sanitizer_common/sanitizer_platform_limits_posix.cc
+@@ -14,6 +14,9 @@
+ 
+ #include "sanitizer_platform.h"
+ 
++// Workaround musl <--> linux conflicting definition of 'struct sysinfo'
++#define _LINUX_SYSINFO_H
++
+ #if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_MAC
+ // Tests in this file assume that off_t-dependent data structures match the
+ // libc ABI. For example, struct dirent here is what readdir() function (as
+@@ -138,12 +141,14 @@ typedef struct user_fpregs elf_fpregset_t;
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+ #include <glob.h>
+-#include <obstack.h>
++#  if !SANITIZER_NONGNU
++#    include <obstack.h>
++#  endif
+ #include <mqueue.h>
+-#include <net/if_ppp.h>
+-#include <netax25/ax25.h>
+-#include <netipx/ipx.h>
+-#include <netrom/netrom.h>
++#include <linux/if_ppp.h>
++#include <linux/ax25.h>
++#include <linux/ipx.h>
++#include <linux/netrom.h>
+ #if HAVE_RPC_XDR_H
+ # include <rpc/xdr.h>
+ #elif HAVE_TIRPC_RPC_XDR_H
+@@ -251,7 +256,7 @@ namespace __sanitizer {
+   unsigned struct_itimerspec_sz = sizeof(struct itimerspec);
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   // Use pre-computed size of struct ustat to avoid <sys/ustat.h> which
+   // has been removed from glibc 2.28.
+ #if defined(__aarch64__) || defined(__s390x__) || defined (__mips64) \
+@@ -322,7 +327,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(ElfW(Phdr));
+ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+ #endif
+ 
+-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
++#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   int glob_nomatch = GLOB_NOMATCH;
+   int glob_altdirfunc = GLOB_ALTDIRFUNC;
+ #endif
+@@ -416,7 +421,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned struct_termios_sz = sizeof(struct termios);
+   unsigned struct_winsize_sz = sizeof(struct winsize);
+ 
+-#if SANITIZER_LINUX
++#if SANITIZER_LINUX && !SANITIZER_NONGNU
+   unsigned struct_arpreq_sz = sizeof(struct arpreq);
+   unsigned struct_cdrom_msf_sz = sizeof(struct cdrom_msf);
+   unsigned struct_cdrom_multisession_sz = sizeof(struct cdrom_multisession);
+@@ -466,7 +471,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned struct_vt_mode_sz = sizeof(struct vt_mode);
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   unsigned struct_ax25_parms_struct_sz = sizeof(struct ax25_parms_struct);
+   unsigned struct_cyclades_monitor_sz = sizeof(struct cyclades_monitor);
+ #if EV_VERSION > (0x010000)
+@@ -834,7 +839,7 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned IOCTL_VT_WAITACTIVE = VT_WAITACTIVE;
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   unsigned IOCTL_CYGETDEFTHRESH = CYGETDEFTHRESH;
+   unsigned IOCTL_CYGETDEFTIMEOUT = CYGETDEFTIMEOUT;
+   unsigned IOCTL_CYGETMON = CYGETMON;
+@@ -989,7 +994,7 @@ CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phdr);
+ CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phnum);
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
++#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ CHECK_TYPE_SIZE(glob_t);
+ CHECK_SIZE_AND_OFFSET(glob_t, gl_pathc);
+ CHECK_SIZE_AND_OFFSET(glob_t, gl_pathv);
+@@ -1023,6 +1028,7 @@ CHECK_TYPE_SIZE(iovec);
+ CHECK_SIZE_AND_OFFSET(iovec, iov_base);
+ CHECK_SIZE_AND_OFFSET(iovec, iov_len);
+ 
++#if !SANITIZER_NONGNU
+ CHECK_TYPE_SIZE(msghdr);
+ CHECK_SIZE_AND_OFFSET(msghdr, msg_name);
+ CHECK_SIZE_AND_OFFSET(msghdr, msg_namelen);
+@@ -1036,6 +1042,7 @@ CHECK_TYPE_SIZE(cmsghdr);
+ CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_len);
+ CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_level);
+ CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_type);
++#endif
+ 
+ #ifndef __GLIBC_PREREQ
+ #define __GLIBC_PREREQ(x, y) 0
+@@ -1145,7 +1152,7 @@ CHECK_SIZE_AND_OFFSET(mntent, mnt_passno);
+ 
+ CHECK_TYPE_SIZE(ether_addr);
+ 
+-#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID
++#if (SANITIZER_LINUX || SANITIZER_FREEBSD) && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ CHECK_TYPE_SIZE(ipc_perm);
+ # if SANITIZER_FREEBSD
+ CHECK_SIZE_AND_OFFSET(ipc_perm, key);
+@@ -1206,7 +1213,7 @@ CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_dstaddr);
+ CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_data);
+ #endif
+ 
+-#if SANITIZER_LINUX
++#if SANITIZER_LINUX && !SANITIZER_NONGNU
+ COMPILER_CHECK(sizeof(__sanitizer_mallinfo) == sizeof(struct mallinfo));
+ #endif
+ 
+@@ -1256,7 +1263,7 @@ COMPILER_CHECK(__sanitizer_XDR_DECODE == XDR_DECODE);
+ COMPILER_CHECK(__sanitizer_XDR_FREE == XDR_FREE);
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ COMPILER_CHECK(sizeof(__sanitizer_FILE) <= sizeof(FILE));
+ CHECK_SIZE_AND_OFFSET(FILE, _flags);
+ CHECK_SIZE_AND_OFFSET(FILE, _IO_read_ptr);
+@@ -1275,7 +1282,7 @@ CHECK_SIZE_AND_OFFSET(FILE, _chain);
+ CHECK_SIZE_AND_OFFSET(FILE, _fileno);
+ #endif
+ 
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+ COMPILER_CHECK(sizeof(__sanitizer__obstack_chunk) <= sizeof(_obstack_chunk));
+ CHECK_SIZE_AND_OFFSET(_obstack_chunk, limit);
+ CHECK_SIZE_AND_OFFSET(_obstack_chunk, prev);
+diff --git a/lib/tsan/rtl/tsan_platform_linux.cc b/lib/tsan/rtl/tsan_platform_linux.cc
+index de989b780..51a97b554 100644
+--- a/lib/tsan/rtl/tsan_platform_linux.cc
++++ b/lib/tsan/rtl/tsan_platform_linux.cc
+@@ -294,7 +294,7 @@ void InitializePlatform() {
+ // This is required to properly "close" the fds, because we do not see internal
+ // closes within glibc. The code is a pure hack.
+ int ExtractResolvFDs(void *state, int *fds, int nfd) {
+-#if SANITIZER_LINUX && !SANITIZER_ANDROID
++#if SANITIZER_LINUX && !SANITIZER_ANDROID && !SANITIZER_NONGNU
+   int cnt = 0;
+   struct __res_state *statp = (struct __res_state*)state;
+   for (int i = 0; i < MAXNS && cnt < nfd; i++) {
+-- 
+2.19.0
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/TLI-musl.patch b/nixpkgs/pkgs/development/compilers/llvm/TLI-musl.patch
new file mode 100644
index 000000000000..1a6908086637
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/TLI-musl.patch
@@ -0,0 +1,35 @@
+From 5c571082fdaf61f6df19d9b7137dc26d71334058 Mon Sep 17 00:00:00 2001
+From: Natanael Copa <ncopa@alpinelinux.org>
+Date: Thu, 18 Feb 2016 10:33:04 +0100
+Subject: [PATCH 2/3] Fix build with musl libc
+
+On musl libc the fopen64 and fopen are the same thing, but for
+compatibility they have a `#define fopen64 fopen`. Same applies for
+fseek64, fstat64, fstatvfs64, ftello64, lstat64, stat64 and tmpfile64.
+---
+ include/llvm/Analysis/TargetLibraryInfo.h | 9 +++++++++
+ 1 file changed, 9 insertions(+)
+
+diff --git a/include/llvm/Analysis/TargetLibraryInfo.h b/include/llvm/Analysis/TargetLibraryInfo.h
+index 7becdf0..7f14427 100644
+--- a/include/llvm/Analysis/TargetLibraryInfo.h
++++ b/include/llvm/Analysis/TargetLibraryInfo.h
+@@ -18,6 +18,15 @@
+ #include "llvm/IR/Module.h"
+ #include "llvm/Pass.h"
+ 
++#undef fopen64
++#undef fseeko64
++#undef fstat64
++#undef fstatvfs64
++#undef ftello64
++#undef lstat64
++#undef stat64
++#undef tmpfile64
++
+ namespace llvm {
+ /// VecDesc - Describes a possible vectorization of a function.
+ /// Function 'VectorFnName' is equivalent to 'ScalarFnName' vectorized
+-- 
+2.7.3
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/aarch64.patch b/nixpkgs/pkgs/development/compilers/llvm/aarch64.patch
new file mode 100644
index 000000000000..205074e48e4e
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/aarch64.patch
@@ -0,0 +1,51 @@
+--- lib/Support/Unix/Memory.inc
++++ lib/Support/Unix/Memory.inc
+@@ -126,8 +126,12 @@
+   Result.Address = Addr;
+   Result.Size = NumPages*PageSize;
+ 
+-  if (PFlags & MF_EXEC)
+-    Memory::InvalidateInstructionCache(Result.Address, Result.Size);
++  // Rely on protectMappedMemory to invalidate instruction cache.
++  if (PFlags & MF_EXEC) {
++    EC = Memory::protectMappedMemory (Result, PFlags);
++    if (EC != std::error_code())
++      return MemoryBlock();
++  }
+ 
+   return Result;
+ }
+@@ -156,15 +160,31 @@
+     return std::error_code(EINVAL, std::generic_category());
+ 
+   int Protect = getPosixProtectionFlags(Flags);
+-
+   uintptr_t Start = alignAddr((uint8_t *)M.Address - PageSize + 1, PageSize);
+   uintptr_t End = alignAddr((uint8_t *)M.Address + M.Size, PageSize);
++
++  bool InvalidateCache = (Flags & MF_EXEC);
++
++#if defined(__arm__) || defined(__aarch64__)
++  // Certain ARM implementations treat icache clear instruction as a memory read,
++  // and CPU segfaults on trying to clear cache on !PROT_READ page.  Therefore we need
++  // to temporarily add PROT_READ for the sake of flushing the instruction caches.
++  if (InvalidateCache && !(Protect & PROT_READ)) {
++    int Result = ::mprotect((void *)Start, End - Start, Protect | PROT_READ);
++    if (Result != 0)
++      return std::error_code(errno, std::generic_category());
++
++    Memory::InvalidateInstructionCache(M.Address, M.Size);
++    InvalidateCache = false;
++  }
++#endif
++
+   int Result = ::mprotect((void *)Start, End - Start, Protect);
+ 
+   if (Result != 0)
+     return std::error_code(errno, std::generic_category());
+ 
+-  if (Flags & MF_EXEC)
++  if (InvalidateCache)
+     Memory::InvalidateInstructionCache(M.Address, M.Size);
+ 
+   return std::error_code();
diff --git a/nixpkgs/pkgs/development/compilers/llvm/dynamiclibrary-musl.patch b/nixpkgs/pkgs/development/compilers/llvm/dynamiclibrary-musl.patch
new file mode 100644
index 000000000000..d5d7f07b5e11
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/dynamiclibrary-musl.patch
@@ -0,0 +1,33 @@
+From d12ecb83d01dcb580dd94f4d57828f33d3eb4c35 Mon Sep 17 00:00:00 2001
+From: Natanael Copa <ncopa@alpinelinux.org>
+Date: Thu, 18 Feb 2016 15:33:21 +0100
+Subject: [PATCH 3/3] Fix DynamicLibrary to build with musl libc
+
+stdin/out/err is part of the libc and not the kernel so we check for the
+specific libc that does the unexpected instead of linux.
+
+This is needed for making it build with musl libc.
+---
+ lib/Support/DynamicLibrary.cpp | 4 ++--
+ 1 file changed, 2 insertions(+), 2 deletions(-)
+
+diff --git a/lib/Support/DynamicLibrary.cpp b/lib/Support/DynamicLibrary.cpp
+index 9a7aeb5..0c1c8f8 100644
+--- a/lib/Support/DynamicLibrary.cpp
++++ b/lib/Support/DynamicLibrary.cpp
+@@ -140,10 +140,10 @@ void* DynamicLibrary::SearchForAddressOfSymbol(const char *symbolName) {
+ #define EXPLICIT_SYMBOL(SYM) \
+    if (!strcmp(symbolName, #SYM)) return &SYM
+ 
+-// On linux we have a weird situation. The stderr/out/in symbols are both
++// On GNU libc we have a weird situation. The stderr/out/in symbols are both
+ // macros and global variables because of standards requirements. So, we
+ // boldly use the EXPLICIT_SYMBOL macro without checking for a #define first.
+-#if defined(__linux__) and !defined(__ANDROID__)
++#if defined(__GLIBC__)
+   {
+     EXPLICIT_SYMBOL(stderr);
+     EXPLICIT_SYMBOL(stdout);
+-- 
+2.7.3
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/fix-llvm-config.patch b/nixpkgs/pkgs/development/compilers/llvm/fix-llvm-config.patch
new file mode 100644
index 000000000000..772c49609275
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/fix-llvm-config.patch
@@ -0,0 +1,13 @@
+diff --git a/utils/llvm-build/llvmbuild/main.py b/utils/llvm-build/llvmbuild/main.py
+index eacefdf60bf..40d25f5cef8 100644
+--- a/utils/llvm-build/llvmbuild/main.py
++++ b/utils/llvm-build/llvmbuild/main.py
+@@ -412,7 +412,7 @@ subdirectories = %s
+             if library_name is None:
+                 library_name_as_cstr = '0'
+             else:
+-                library_name_as_cstr = '"lib%s.a"' % library_name
++                library_name_as_cstr = '"lib%s.so"' % library_name
+             f.write('  { "%s", %s, %d, { %s } },\n' % (
+                 name, library_name_as_cstr, is_installed,
+                 ', '.join('"%s"' % dep
diff --git a/nixpkgs/pkgs/development/compilers/llvm/libcxx-0001-musl-hacks.patch b/nixpkgs/pkgs/development/compilers/llvm/libcxx-0001-musl-hacks.patch
new file mode 100644
index 000000000000..bcb5ad8cfb87
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/libcxx-0001-musl-hacks.patch
@@ -0,0 +1,39 @@
+From 1c936d7fda3275265e37f93697232a1ed652390f Mon Sep 17 00:00:00 2001
+From: Will Dietz <w@wdtz.org>
+Date: Sat, 9 Jul 2016 19:22:54 -0500
+Subject: [PATCH] musl fixes/hacks
+
+Conflicts:
+
+	include/__config
+	include/locale
+	src/locale.cpp
+---
+ include/locale |    4 ++--
+ 1 files changed, 2 insertions(+), 2 deletions(-)
+
+diff --git a/include/locale b/include/locale
+index 3d804e8..9b01f5b 100644
+--- a/include/locale
++++ b/include/locale
+@@ -695,7 +695,7 @@ __num_get_signed_integral(const char* __a, const char* __a_end,
+         typename remove_reference<decltype(errno)>::type __save_errno = errno;
+         errno = 0;
+         char *__p2;
+-        long long __ll = strtoll_l(__a, &__p2, __base, _LIBCPP_GET_C_LOCALE);
++        long long __ll = strtoll(__a, &__p2, __base);
+         typename remove_reference<decltype(errno)>::type __current_errno = errno;
+         if (__current_errno == 0)
+             errno = __save_errno;
+@@ -735,7 +735,7 @@ __num_get_unsigned_integral(const char* __a, const char* __a_end,
+         typename remove_reference<decltype(errno)>::type __save_errno = errno;
+         errno = 0;
+         char *__p2;
+-        unsigned long long __ll = strtoull_l(__a, &__p2, __base, _LIBCPP_GET_C_LOCALE);
++        unsigned long long __ll = strtoull(__a, &__p2, __base);
+         typename remove_reference<decltype(errno)>::type __current_errno = errno;
+         if (__current_errno == 0)
+             errno = __save_errno;
+-- 
+1.7.1
+
diff --git a/nixpkgs/pkgs/development/compilers/llvm/libcxx-max_align_t.patch b/nixpkgs/pkgs/development/compilers/llvm/libcxx-max_align_t.patch
new file mode 100644
index 000000000000..060be5b23de8
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/libcxx-max_align_t.patch
@@ -0,0 +1,54 @@
+From 917331c88bd2afce0cf0fdbcab55a64541b5bcf0 Mon Sep 17 00:00:00 2001
+From: "David L. Jones" <dlj@google.com>
+Date: Fri, 10 Feb 2017 01:27:42 +0000
+Subject: [PATCH] Check for musl-libc's max_align_t in addition to other
+ variants.
+
+Summary:
+Libcxx will define its own max_align_t when it is not available. However, the
+availability checks today only check for Clang's definition and GCC's
+definition. In particular, it does not check for musl's definition, which is the
+same as GCC's but guarded with a different macro.
+
+Reviewers: mclow.lists, EricWF
+
+Reviewed By: EricWF
+
+Subscribers: chandlerc, cfe-commits
+
+Differential Revision: https://reviews.llvm.org/D28478
+
+git-svn-id: https://llvm.org/svn/llvm-project/libcxx/trunk@294683 91177308-0d34-0410-b5e6-96231b3b80d8
+---
+ include/cstddef  | 3 ++-
+ include/stddef.h | 3 ++-
+ 2 files changed, 4 insertions(+), 2 deletions(-)
+
+diff --git a/include/cstddef b/include/cstddef
+index edd106c00..103898b7d 100644
+--- a/include/cstddef
++++ b/include/cstddef
+@@ -48,7 +48,8 @@ _LIBCPP_BEGIN_NAMESPACE_STD
+ using ::ptrdiff_t;
+ using ::size_t;
+ 
+-#if defined(__CLANG_MAX_ALIGN_T_DEFINED) || defined(_GCC_MAX_ALIGN_T)
++#if defined(__CLANG_MAX_ALIGN_T_DEFINED) || defined(_GCC_MAX_ALIGN_T) || \
++    defined(__DEFINED_max_align_t)
+ // Re-use the compiler's <stddef.h> max_align_t where possible.
+ using ::max_align_t;
+ #else
+diff --git a/include/stddef.h b/include/stddef.h
+index 8841bbea2..faf8552d8 100644
+--- a/include/stddef.h
++++ b/include/stddef.h
+@@ -53,7 +53,8 @@ using std::nullptr_t;
+ }
+ 
+ // Re-use the compiler's <stddef.h> max_align_t where possible.
+-#if !defined(__CLANG_MAX_ALIGN_T_DEFINED) && !defined(_GCC_MAX_ALIGN_T)
++#if !defined(__CLANG_MAX_ALIGN_T_DEFINED) && !defined(_GCC_MAX_ALIGN_T) && \
++    !defined(__DEFINED_max_align_t)
+ typedef long double max_align_t;
+ #endif
+ 
diff --git a/nixpkgs/pkgs/development/compilers/llvm/multi.nix b/nixpkgs/pkgs/development/compilers/llvm/multi.nix
new file mode 100644
index 000000000000..b4f2f8f9d6f6
--- /dev/null
+++ b/nixpkgs/pkgs/development/compilers/llvm/multi.nix
@@ -0,0 +1,48 @@
+{ runCommand,
+clang,
+gcc64,
+gcc32,
+glibc_multi
+}:
+
+let
+  combine = basegcc: runCommand "combine-gcc-libc" {} ''
+    mkdir -p $out
+    cp -r ${basegcc.cc}/lib $out/lib
+
+    chmod u+rw -R $out/lib
+    cp -r ${basegcc.libc}/lib/* $(ls -d $out/lib/gcc/*/*)
+  '';
+  gcc_multi_sysroot = runCommand "gcc-multi-sysroot" {} ''
+    mkdir -p $out/lib/gcc
+
+    ln -s ${combine gcc64}/lib/gcc/* $out/lib/gcc/
+    ln -s ${combine gcc32}/lib/gcc/* $out/lib/gcc/
+    # XXX: This shouldn't be needed, clang just doesn't look for "i686-unknown"
+    ln -s $out/lib/gcc/i686-unknown-linux-gnu $out/lib/gcc/i686-pc-linux-gnu
+
+
+    # includes
+    ln -s ${glibc_multi.dev}/include $out/
+
+    # dynamic linkers
+    mkdir -p $out/lib/32
+    ln -s ${glibc_multi.out}/lib/ld-linux* $out/lib
+    ln -s ${glibc_multi.out}/lib/32/ld-linux* $out/lib/32/
+  '';
+
+  clangMulti = clang.override {
+    # Only used for providing expected structure re:dynamic linkers, AFAIK
+    # Most of the magic is done by setting the --gcc-toolchain option below
+    libc = gcc_multi_sysroot;
+
+    bintools = clang.bintools.override {
+      libc = gcc_multi_sysroot;
+    };
+
+    extraBuildCommands = ''
+      sed -e '$a --gcc-toolchain=${gcc_multi_sysroot}' -i $out/nix-support/libc-cflags
+    '';
+  };
+
+in clangMulti