diff --git a/packages/gcc/darwin/apfs.patch b/packages/gcc/darwin/apfs.patch
new file mode 100644
index 0000000000000000000000000000000000000000..d1f9d56667dd9cf95e855ec71e38899ef9b6562a
--- /dev/null
+++ b/packages/gcc/darwin/apfs.patch
@@ -0,0 +1,12 @@
+diff -uNr gcc-7.2.0.orig/libstdc++-v3/include/Makefile.in gcc-7.2.0/libstdc++-v3/include/Makefile.in
+--- gcc-7.2.0.orig/libstdc++-v3/include/Makefile.in     2017-07-25 14:05:07.000000000 -0400
++++ gcc-7.2.0/libstdc++-v3/include/Makefile.in  2017-09-02 12:22:08.000000000 -0400
+@@ -1764,6 +1764,8 @@
+ @GLIBCXX_HOSTED_TRUE@install-data-local: install-headers
+ @GLIBCXX_HOSTED_FALSE@install-data-local: install-freestanding-headers
+ 
++.NOTPARALLEL: install-headers
++
+ # This is a subset of the full install-headers rule.  We only need <ciso646>,
+ # <cstddef>, <cfloat>, <limits>, <climits>, <cstdint>, <cstdlib>, <new>,
+ # <typeinfo>, <exception>, <initializer_list>, <cstdalign>, <cstdarg>,
diff --git a/packages/gcc/darwin/clang13.patch b/packages/gcc/darwin/clang13.patch
new file mode 100644
index 0000000000000000000000000000000000000000..ac3bfcbe244c08e0672ad73fa9e10f067f6b78a7
--- /dev/null
+++ b/packages/gcc/darwin/clang13.patch
@@ -0,0 +1,32 @@
+--- a/gcc/genconditions.c	2019-01-01 12:37:19.064943662 +0100
++++ b/gcc/genconditions.c	2019-10-11 10:57:11.464595789 +0200
+@@ -57,8 +57,9 @@ write_header (void)
+ \n\
+ /* It is necessary, but not entirely safe, to include the headers below\n\
+    in a generator program.  As a defensive measure, don't do so when the\n\
+-   table isn't going to have anything in it.  */\n\
+-#if GCC_VERSION >= 3001\n\
++   table isn't going to have anything in it.\n\
++   Clang 9 is buggy and doesn't handle __builtin_constant_p correctly.  */\n\
++#if GCC_VERSION >= 3001 && __clang_major__ < 9\n\
+ \n\
+ /* Do not allow checking to confuse the issue.  */\n\
+ #undef CHECKING_P\n\
+@@ -170,7 +171,7 @@ struct c_test\n\
+    vary at run time.  It works in 3.0.1 and later; 3.0 only when not\n\
+    optimizing.  */\n\
+ \n\
+-#if GCC_VERSION >= 3001\n\
++#if GCC_VERSION >= 3001 && __clang_major__ < 9\n\
+ static const struct c_test insn_conditions[] = {\n");
+ 
+   traverse_c_tests (write_one_condition, 0);
+@@ -191,7 +192,7 @@ write_writer (void)
+ 	"  unsigned int i;\n"
+         "  const char *p;\n"
+         "  puts (\"(define_conditions [\");\n"
+-	"#if GCC_VERSION >= 3001\n"
++	"#if GCC_VERSION >= 3001 && __clang_major__ < 9\n"
+ 	"  for (i = 0; i < ARRAY_SIZE (insn_conditions); i++)\n"
+ 	"    {\n"
+ 	"      printf (\"  (%d \\\"\", insn_conditions[i].value);\n"
diff --git a/packages/gcc/darwin/gcc-4.9.patch1 b/packages/gcc/darwin/gcc-4.9.patch1
new file mode 100644
index 0000000000000000000000000000000000000000..444e292786df41346a3a1cc6267bba587408a007
--- /dev/null
+++ b/packages/gcc/darwin/gcc-4.9.patch1
@@ -0,0 +1,42 @@
+diff --git a/gcc/configure b/gcc/configure
+index 9523773..52b0bf7 100755
+--- a/gcc/configure
++++ b/gcc/configure
+@@ -24884,7 +24884,7 @@ if test "${gcc_cv_as_ix86_filds+set}" = set; then :
+ else
+   gcc_cv_as_ix86_filds=no
+   if test x$gcc_cv_as != x; then
+-    $as_echo 'filds mem; fists mem' > conftest.s
++    $as_echo 'filds (%ebp); fists (%ebp)' > conftest.s
+     if { ac_try='$gcc_cv_as $gcc_cv_as_flags  -o conftest.o conftest.s >&5'
+   { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5
+   (eval $ac_try) 2>&5
+@@ -24915,7 +24915,7 @@ if test "${gcc_cv_as_ix86_fildq+set}" = set; then :
+ else
+   gcc_cv_as_ix86_fildq=no
+   if test x$gcc_cv_as != x; then
+-    $as_echo 'fildq mem; fistpq mem' > conftest.s
++    $as_echo 'fildq (%ebp); fistpq (%ebp)' > conftest.s
+     if { ac_try='$gcc_cv_as $gcc_cv_as_flags  -o conftest.o conftest.s >&5'
+   { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5
+   (eval $ac_try) 2>&5
+diff --git a/gcc/configure.ac b/gcc/configure.ac
+index 68b0ee8..bd53978 100644
+--- a/gcc/configure.ac
++++ b/gcc/configure.ac
+@@ -3869,13 +3869,13 @@ foo:	nop
+ 
+     gcc_GAS_CHECK_FEATURE([filds and fists mnemonics],
+        gcc_cv_as_ix86_filds,,,
+-       [filds mem; fists mem],,
++       [filds (%ebp); fists (%ebp)],,
+        [AC_DEFINE(HAVE_AS_IX86_FILDS, 1,
+          [Define if your assembler uses filds and fists mnemonics.])])
+ 
+     gcc_GAS_CHECK_FEATURE([fildq and fistpq mnemonics],
+        gcc_cv_as_ix86_fildq,,,
+-       [fildq mem; fistpq mem],,
++       [fildq (%ebp); fistpq (%ebp)],,
+        [AC_DEFINE(HAVE_AS_IX86_FILDQ, 1,
+          [Define if your assembler uses fildq and fistq mnemonics.])])
+ 
diff --git a/packages/gcc/darwin/gcc-4.9.patch2 b/packages/gcc/darwin/gcc-4.9.patch2
new file mode 100644
index 0000000000000000000000000000000000000000..b065997f453926e20d285f8a5e6555d9cd2e8f96
--- /dev/null
+++ b/packages/gcc/darwin/gcc-4.9.patch2
@@ -0,0 +1,28 @@
+From 82f81877458ea372176eabb5de36329431dce99b Mon Sep 17 00:00:00 2001
+From: Iain Sandoe <iain@codesourcery.com>
+Date: Sat, 21 Dec 2013 00:30:18 +0000
+Subject: [PATCH] don't try to mark local symbols as no-dead-strip
+
+---
+ gcc/config/darwin.c | 5 +++++
+ 1 file changed, 5 insertions(+)
+
+diff --git a/gcc/config/darwin.c b/gcc/config/darwin.c
+index 40804b8..0080299 100644
+--- a/gcc/config/darwin.c
++++ b/gcc/config/darwin.c
+@@ -1259,6 +1259,11 @@ darwin_encode_section_info (tree decl, rtx rtl, int first ATTRIBUTE_UNUSED)
+ void
+ darwin_mark_decl_preserved (const char *name)
+ {
++  /* Actually we shouldn't mark any local symbol this way, but for now
++     this only happens with ObjC meta-data.  */
++  if (darwin_label_is_anonymous_local_objc_name (name))
++    return;
++
+   fprintf (asm_out_file, "\t.no_dead_strip ");
+   assemble_name (asm_out_file, name);
+   fputc ('\n', asm_out_file);
+-- 
+2.2.1
+
diff --git a/packages/gcc/darwin/gcc-6.1.0-jit.patch b/packages/gcc/darwin/gcc-6.1.0-jit.patch
new file mode 100644
index 0000000000000000000000000000000000000000..8cc4405de49458db88df59ad28b41c14aec74954
--- /dev/null
+++ b/packages/gcc/darwin/gcc-6.1.0-jit.patch
@@ -0,0 +1,21 @@
+# Fix for libgccjit.so linkage on Darwin
+# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=64089
+# https://github.com/Homebrew/homebrew-core/issues/1872#issuecomment-225625332
+# https://github.com/Homebrew/homebrew-core/issues/1872#issuecomment-225626490
+
+# Stolen from Homebrew:
+# https://raw.githubusercontent.com/Homebrew/formula-patches/e9e0ee09389a54cc4c8fe1c24ebca3cd765ed0ba/gcc/6.1.0-jit.patch
+diff --git a/gcc/jit/Make-lang.in b/gcc/jit/Make-lang.in
+index 44d0750..4df2a9c 100644
+--- a/gcc/jit/Make-lang.in
++++ b/gcc/jit/Make-lang.in
+@@ -85,8 +85,7 @@ $(LIBGCCJIT_FILENAME): $(jit_OBJS) \
+	     $(jit_OBJS) libbackend.a libcommon-target.a libcommon.a \
+	     $(CPPLIB) $(LIBDECNUMBER) $(LIBS) $(BACKENDLIBS) \
+	     $(EXTRA_GCC_OBJS) \
+-	     -Wl,--version-script=$(srcdir)/jit/libgccjit.map \
+-	     -Wl,-soname,$(LIBGCCJIT_SONAME)
++	     -Wl,-install_name,$(LIBGCCJIT_SONAME)
+
+ $(LIBGCCJIT_SONAME_SYMLINK): $(LIBGCCJIT_FILENAME)
+	ln -sf $(LIBGCCJIT_FILENAME) $(LIBGCCJIT_SONAME_SYMLINK)
diff --git a/packages/gcc/darwin/gcc-7.1.0-headerpad.patch b/packages/gcc/darwin/gcc-7.1.0-headerpad.patch
new file mode 100644
index 0000000000000000000000000000000000000000..11ca2d0e4d711ac45a5773a815caf43c8ab82a92
--- /dev/null
+++ b/packages/gcc/darwin/gcc-7.1.0-headerpad.patch
@@ -0,0 +1,19 @@
+# Use -headerpad_max_install_names in the build,
+# otherwise lto1 load commands cannot be edited on El Capitan
+
+# Stolen from Homebrew:
+# https://raw.githubusercontent.com/Homebrew/formula-patches/32cf103/gcc/7.1.0-headerpad.patch
+
+diff --git a/config/mh-darwin b/config/mh-darwin
+index 148b730..c2318b5 100644
+--- a/config/mh-darwin
++++ b/config/mh-darwin
+@@ -16,7 +16,7 @@ DARWIN_GCC_MDYNAMIC_NO_PIC := \
+ DARWIN_NO_PIE := `case ${host} in *-*-darwin[1][1-9]*) echo -Wl,-no_pie ;; esac;`
+ 
+ BOOT_CFLAGS += $(DARWIN_MDYNAMIC_NO_PIC)
+-BOOT_LDFLAGS += $(DARWIN_NO_PIE)
++BOOT_LDFLAGS += $(DARWIN_NO_PIE) -Wl,-headerpad_max_install_names
+ 
+ # Similarly, for cross-compilation.
+ STAGE1_CFLAGS += $(DARWIN_MDYNAMIC_NO_PIC)
diff --git a/packages/gcc/darwin/headers-10.13-fix.patch b/packages/gcc/darwin/headers-10.13-fix.patch
new file mode 100644
index 0000000000000000000000000000000000000000..3dbfde0255aa38833f6c162dd22cb30231c4bd58
--- /dev/null
+++ b/packages/gcc/darwin/headers-10.13-fix.patch
@@ -0,0 +1,127 @@
+diff -pur fixincludes/fixincl.x gcc-5.5.0/fixincludes/fixincl.x
+--- a/fixincludes/fixincl.x	2017-01-30 17:08:42.000000000 +0100
++++ b/fixincludes/fixincl.x	2017-12-21 14:34:35.000000000 +0100
+@@ -1,12 +1,12 @@
+ /*  -*- buffer-read-only: t -*- vi: set ro:
+- * 
++ *
+  * DO NOT EDIT THIS FILE   (fixincl.x)
+- * 
+- * It has been AutoGen-ed  January  5, 2017 at 06:05:06 PM by AutoGen 5.16.2
++ *
++ * It has been AutoGen-ed  December 21, 2017 at 02:34:35 PM by AutoGen 5.18.7
+  * From the definitions    inclhack.def
+  * and the template file   fixincl
+  */
+-/* DO NOT SVN-MERGE THIS FILE, EITHER Thu Jan  5 18:05:06 CET 2017
++/* DO NOT SVN-MERGE THIS FILE, EITHER Thu Dec 21 14:34:35 CET 2017
+  *
+  * You must regenerate it.  Use the ./genfixes script.
+  *
+@@ -15,7 +15,7 @@
+  * certain ANSI-incompatible system header files which are fixed to work
+  * correctly with ANSI C and placed in a directory that GNU C will search.
+  *
+- * This file contains 240 fixup descriptions.
++ * This file contains 241 fixup descriptions.
+  *
+  * See README for more information.
+  *
+@@ -2579,6 +2579,43 @@ extern \"C\" {\n\
+ 
+ /* * * * * * * * * * * * * * * * * * * * * * * * * *
+  *
++ *  Description of Darwin_Osavailability fix
++ */
++tSCC zDarwin_OsavailabilityName[] =
++     "darwin_osavailability";
++
++/*
++ *  File name selection pattern
++ */
++tSCC zDarwin_OsavailabilityList[] =
++  "os/availability.h\0";
++/*
++ *  Machine/OS name selection pattern
++ */
++tSCC* apzDarwin_OsavailabilityMachs[] = {
++        "*-*-darwin*",
++        (const char*)NULL };
++
++/*
++ *  content selection pattern - do fix if pattern found
++ */
++tSCC zDarwin_OsavailabilitySelect0[] =
++       "#define[ \t]+__(API_[A-Z_]*)\\(\\.\\.\\.\\)";
++
++#define    DARWIN_OSAVAILABILITY_TEST_CT  1
++static tTestDesc aDarwin_OsavailabilityTests[] = {
++  { TT_EGREP,    zDarwin_OsavailabilitySelect0, (regex_t*)NULL }, };
++
++/*
++ *  Fix Command Arguments for Darwin_Osavailability
++ */
++static const char* apzDarwin_OsavailabilityPatch[] = {
++    "format",
++    "#define %1(...)",
++    (char*)NULL };
++
++/* * * * * * * * * * * * * * * * * * * * * * * * * *
++ *
+  *  Description of Darwin_9_Long_Double_Funcs_2 fix
+  */
+ tSCC zDarwin_9_Long_Double_Funcs_2Name[] =
+@@ -9818,9 +9855,9 @@ static const char* apzX11_SprintfPatch[]
+  *
+  *  List of all fixes
+  */
+-#define REGEX_COUNT          276
++#define REGEX_COUNT          277
+ #define MACH_LIST_SIZE_LIMIT 187
+-#define FIX_COUNT            240
++#define FIX_COUNT            241
+ 
+ /*
+  *  Enumerate the fixes
+@@ -9885,6 +9922,7 @@ typedef enum {
+     CTRL_QUOTES_DEF_FIXIDX,
+     CTRL_QUOTES_USE_FIXIDX,
+     CXX_UNREADY_FIXIDX,
++    DARWIN_OSAVAILABILITY_FIXIDX,
+     DARWIN_9_LONG_DOUBLE_FUNCS_2_FIXIDX,
+     DARWIN_EXTERNC_FIXIDX,
+     DARWIN_GCC4_BREAKAGE_FIXIDX,
+@@ -10364,6 +10402,11 @@ tFixDesc fixDescList[ FIX_COUNT ] = {
+      CXX_UNREADY_TEST_CT, FD_MACH_ONLY | FD_SUBROUTINE,
+      aCxx_UnreadyTests,   apzCxx_UnreadyPatch, 0 },
+ 
++  {  zDarwin_OsavailabilityName,    zDarwin_OsavailabilityList,
++     apzDarwin_OsavailabilityMachs,
++     DARWIN_OSAVAILABILITY_TEST_CT, FD_MACH_ONLY | FD_SUBROUTINE,
++     aDarwin_OsavailabilityTests,   apzDarwin_OsavailabilityPatch, 0 },
++
+   {  zDarwin_9_Long_Double_Funcs_2Name,    zDarwin_9_Long_Double_Funcs_2List,
+      apzDarwin_9_Long_Double_Funcs_2Machs,
+      DARWIN_9_LONG_DOUBLE_FUNCS_2_TEST_CT, FD_MACH_ONLY | FD_SUBROUTINE,
+diff -pur fixincludes/inclhack.def gcc-5.5.0/fixincludes/inclhack.def
+--- a/fixincludes/inclhack.def	2017-01-30 17:08:42.000000000 +0100
++++ b/fixincludes/inclhack.def	2017-12-21 14:34:28.000000000 +0100
+@@ -1337,6 +1337,18 @@ fix = {
+     test_text = "extern void* malloc( size_t );";
+ };
+ 
++fix = {
++    hackname  = darwin_osavailability;
++    mach      = "*-*-darwin*";
++    files     = os/availability.h;
++    select    = "#define[ \t]+__(API_[A-Z_]*)\\(\\.\\.\\.\\)";
++    c_fix     = format;
++    c_fix_arg = "#define %1(...)";
++
++    test_text = "#define __API_AVAILABLE(...)\n"
++		"#define API_AVAILABLE(...)\n";
++};
++
+ /*
+  *  For the AAB_darwin7_9_long_double_funcs fix to be useful,
+  *  you have to not use "" includes.
diff --git a/packages/gcc/gcc-backport.patch b/packages/gcc/gcc-backport.patch
new file mode 100644
index 0000000000000000000000000000000000000000..f9fab68f23700bfe48f5a7948bb64ec2d0fb1ff7
--- /dev/null
+++ b/packages/gcc/gcc-backport.patch
@@ -0,0 +1,138 @@
+2016-02-20  Bernd Edlinger  <bernd.edlinger@hotmail.de>
+
+	Backported from mainline
+	2016-02-19  Jakub Jelinek  <jakub@redhat.com>
+		    Bernd Edlinger  <bernd.edlinger@hotmail.de>
+
+	* Make-lang.in: Invoke gperf with -L C++.
+ 	* cfns.gperf: Remove prototypes for hash and libc_name_p
+ 	inlines.
+ 	* cfns.h: Regenerated.
+	* except.c (nothrow_libfn_p): Adjust.
+
+Index: gcc/cp/Make-lang.in
+===================================================================
+--- a/gcc/cp/Make-lang.in	(revision 233574)
++++ b/gcc/cp/Make-lang.in	(working copy)
+@@ -111,7 +111,7 @@ else
+ # deleting the $(srcdir)/cp/cfns.h file.
+ $(srcdir)/cp/cfns.h:
+ endif
+-	gperf -o -C -E -k '1-6,$$' -j1 -D -N 'libc_name_p' -L ANSI-C \
++	gperf -o -C -E -k '1-6,$$' -j1 -D -N 'libc_name_p' -L C++ \
+ 		$(srcdir)/cp/cfns.gperf --output-file $(srcdir)/cp/cfns.h
+ 
+ #
+Index: gcc/cp/cfns.gperf
+===================================================================
+--- a/gcc/cp/cfns.gperf	(revision 233574)
++++ b/gcc/cp/cfns.gperf	(working copy)
+@@ -1,3 +1,5 @@
++%language=C++
++%define class-name libc_name
+ %{
+ /* Copyright (C) 2000-2015 Free Software Foundation, Inc.
+ 
+@@ -16,14 +18,6 @@ for more details.
+ You should have received a copy of the GNU General Public License
+ along with GCC; see the file COPYING3.  If not see
+ <http://www.gnu.org/licenses/>.  */
+-#ifdef __GNUC__
+-__inline
+-#endif
+-static unsigned int hash (const char *, unsigned int);
+-#ifdef __GNUC__
+-__inline
+-#endif
+-const char * libc_name_p (const char *, unsigned int);
+ %}
+ %%
+ # The standard C library functions, for feeding to gperf; the result is used
+Index: gcc/cp/cfns.h
+===================================================================
+--- a/gcc/cp/cfns.h	(revision 233574)
++++ b/gcc/cp/cfns.h	(working copy)
+@@ -1,5 +1,5 @@
+-/* ANSI-C code produced by gperf version 3.0.3 */
+-/* Command-line: gperf -o -C -E -k '1-6,$' -j1 -D -N libc_name_p -L ANSI-C cfns.gperf  */
++/* C++ code produced by gperf version 3.0.4 */
++/* Command-line: gperf -o -C -E -k '1-6,$' -j1 -D -N libc_name_p -L C++ --output-file cfns.h cfns.gperf  */
+ 
+ #if !((' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \
+       && ('%' == 37) && ('&' == 38) && ('\'' == 39) && ('(' == 40) \
+@@ -28,7 +28,7 @@
+ #error "gperf generated tables don't work with this execution character set. Please report a bug to <bug-gnu-gperf@gnu.org>."
+ #endif
+ 
+-#line 1 "cfns.gperf"
++#line 3 "cfns.gperf"
+ 
+ /* Copyright (C) 2000-2015 Free Software Foundation, Inc.
+ 
+@@ -47,26 +47,19 @@ for more details.
+ You should have received a copy of the GNU General Public License
+ along with GCC; see the file COPYING3.  If not see
+ <http://www.gnu.org/licenses/>.  */
+-#ifdef __GNUC__
+-__inline
+-#endif
+-static unsigned int hash (const char *, unsigned int);
+-#ifdef __GNUC__
+-__inline
+-#endif
+-const char * libc_name_p (const char *, unsigned int);
+ /* maximum key range = 391, duplicates = 0 */
+ 
+-#ifdef __GNUC__
+-__inline
+-#else
+-#ifdef __cplusplus
+-inline
+-#endif
+-#endif
+-static unsigned int
+-hash (register const char *str, register unsigned int len)
++class libc_name
+ {
++private:
++  static inline unsigned int hash (const char *str, unsigned int len);
++public:
++  static const char *libc_name_p (const char *str, unsigned int len);
++};
++
++inline unsigned int
++libc_name::hash (register const char *str, register unsigned int len)
++{
+   static const unsigned short asso_values[] =
+     {
+       400, 400, 400, 400, 400, 400, 400, 400, 400, 400,
+@@ -122,14 +115,8 @@ along with GCC; see the file COPYING3.  If not see
+   return hval + asso_values[(unsigned char)str[len - 1]];
+ }
+ 
+-#ifdef __GNUC__
+-__inline
+-#ifdef __GNUC_STDC_INLINE__
+-__attribute__ ((__gnu_inline__))
+-#endif
+-#endif
+ const char *
+-libc_name_p (register const char *str, register unsigned int len)
++libc_name::libc_name_p (register const char *str, register unsigned int len)
+ {
+   enum
+     {
+Index: gcc/cp/except.c
+===================================================================
+--- a/gcc/cp/except.c	(revision 233574)
++++ b/gcc/cp/except.c	(working copy)
+@@ -1040,7 +1040,8 @@ nothrow_libfn_p (const_tree fn)
+      unless the system headers are playing rename tricks, and if
+      they are, we don't want to be confused by them.  */
+   id = DECL_NAME (fn);
+-  return !!libc_name_p (IDENTIFIER_POINTER (id), IDENTIFIER_LENGTH (id));
++  return !!libc_name::libc_name_p (IDENTIFIER_POINTER (id),
++				   IDENTIFIER_LENGTH (id));
+ }
+ 
+ /* Returns nonzero if an exception of type FROM will be caught by a
diff --git a/packages/gcc/glibc-2.31-libsanitizer-1-gcc-6.patch b/packages/gcc/glibc-2.31-libsanitizer-1-gcc-6.patch
new file mode 100644
index 0000000000000000000000000000000000000000..4187b812d5d3ea41a60dd1de4faf0c55e6ac850d
--- /dev/null
+++ b/packages/gcc/glibc-2.31-libsanitizer-1-gcc-6.patch
@@ -0,0 +1,39 @@
+From ce9568e9e9cf6094be30e748821421e703754ffc Mon Sep 17 00:00:00 2001
+From: Jakub Jelinek <jakub@redhat.com>
+Date: Fri, 8 Nov 2019 19:53:18 +0100
+Subject: [PATCH] backport: re PR sanitizer/92154 (new glibc breaks arm
+ bootstrap due to libsanitizer)
+
+	Backported from mainline
+	2019-10-22  Tamar Christina  <tamar.christina@arm.com>
+	Backported for version 5.3.0 <= gcc <= 6.5.0
+	2020-06-05  John L. Jolly  <john.jolly@gmail.com>
+
+	PR sanitizer/92154
+	* sanitizer_common/sanitizer_platform_limits_posix.cc:
+	Cherry-pick compiler-rt revision r375220.
+
+From-SVN: r277981
+---
+ libsanitizer/ChangeLog                                   | 9 +++++++++
+ .../sanitizer_common/sanitizer_platform_limits_posix.cc  | 6 +++++-
+ 2 files changed, 14 insertions(+), 1 deletion(-)
+
+diff --git a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+index 6cd4a5bac8b0..06a605ff4670 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+@@ -1130,8 +1130,12 @@ CHECK_SIZE_AND_OFFSET(ipc_perm, uid);
+ #ifndef __GLIBC_PREREQ
+ #define __GLIBC_PREREQ(x, y) 0
+ #endif
+-#if !defined(__aarch64__) || !SANITIZER_LINUX || __GLIBC_PREREQ (2, 21)
++#if (!defined(__aarch64__) || !SANITIZER_LINUX || __GLIBC_PREREQ (2, 21)) && \
++    !defined(__arm__)
+ /* On aarch64 glibc 2.20 and earlier provided incorrect mode field.  */
++/* On Arm glibc 2.31 and later provide a different mode field, this field is
++   never used by libsanitizer so we can simply ignore this assert for all glibc
++   versions.  */
+ CHECK_SIZE_AND_OFFSET(ipc_perm, mode);
+ #endif
+ 
diff --git a/packages/gcc/glibc-2.31-libsanitizer-1.patch b/packages/gcc/glibc-2.31-libsanitizer-1.patch
new file mode 100644
index 0000000000000000000000000000000000000000..96037707d3cf11c993010fde0e689d91e6aa8848
--- /dev/null
+++ b/packages/gcc/glibc-2.31-libsanitizer-1.patch
@@ -0,0 +1,37 @@
+From ce9568e9e9cf6094be30e748821421e703754ffc Mon Sep 17 00:00:00 2001
+From: Jakub Jelinek <jakub@redhat.com>
+Date: Fri, 8 Nov 2019 19:53:18 +0100
+Subject: [PATCH] backport: re PR sanitizer/92154 (new glibc breaks arm
+ bootstrap due to libsanitizer)
+
+	Backported from mainline
+	2019-10-22  Tamar Christina  <tamar.christina@arm.com>
+
+	PR sanitizer/92154
+	* sanitizer_common/sanitizer_platform_limits_posix.cc:
+	Cherry-pick compiler-rt revision r375220.
+
+From-SVN: r277981
+---
+ libsanitizer/ChangeLog                                   | 9 +++++++++
+ .../sanitizer_common/sanitizer_platform_limits_posix.cc  | 6 +++++-
+ 2 files changed, 14 insertions(+), 1 deletion(-)
+
+diff --git a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+index 6cd4a5bac8b0..06a605ff4670 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+@@ -1156,8 +1156,12 @@ CHECK_SIZE_AND_OFFSET(ipc_perm, uid);
+ CHECK_SIZE_AND_OFFSET(ipc_perm, gid);
+ CHECK_SIZE_AND_OFFSET(ipc_perm, cuid);
+ CHECK_SIZE_AND_OFFSET(ipc_perm, cgid);
+-#if !defined(__aarch64__) || !SANITIZER_LINUX || __GLIBC_PREREQ (2, 21)
++#if (!defined(__aarch64__) || !SANITIZER_LINUX || __GLIBC_PREREQ (2, 21)) && \
++    !defined(__arm__)
+ /* On aarch64 glibc 2.20 and earlier provided incorrect mode field.  */
++/* On Arm glibc 2.31 and later provide a different mode field, this field is
++   never used by libsanitizer so we can simply ignore this assert for all glibc
++   versions.  */
+ CHECK_SIZE_AND_OFFSET(ipc_perm, mode);
+ #endif
+ 
diff --git a/packages/gcc/glibc-2.31-libsanitizer-2-gcc-6.patch b/packages/gcc/glibc-2.31-libsanitizer-2-gcc-6.patch
new file mode 100644
index 0000000000000000000000000000000000000000..755db173ffba61ade4c3fd5d8c6a5990ded63eaa
--- /dev/null
+++ b/packages/gcc/glibc-2.31-libsanitizer-2-gcc-6.patch
@@ -0,0 +1,69 @@
+From 75003cdd23c310ec385344e8040d490e8dd6d2be Mon Sep 17 00:00:00 2001
+From: Jakub Jelinek <jakub@redhat.com>
+Date: Fri, 20 Dec 2019 17:58:35 +0100
+Subject: [PATCH] backport: re PR sanitizer/92154 (new glibc breaks arm
+ bootstrap due to libsanitizer)
+
+	Backported from mainline
+	2019-11-26  Jakub Jelinek  <jakub@redhat.com>
+	Backported for version 5.3.0 <= gcc <= 6.5.0
+	2020-06-05  John L. Jolly  <john.jolly@gmail.com>
+
+	PR sanitizer/92154
+	* sanitizer_common/sanitizer_platform_limits_posix.h: Cherry-pick
+	llvm-project revision 947f9692440836dcb8d88b74b69dd379d85974ce.
+	* sanitizer_common/sanitizer_platform_limits_posix.cc: Likewise.
+
+From-SVN: r279653
+---
+ libsanitizer/ChangeLog                            | 10 ++++++++++
+ .../sanitizer_platform_limits_posix.cc            |  9 +++------
+ .../sanitizer_platform_limits_posix.h             | 15 +--------------
+ 3 files changed, 14 insertions(+), 20 deletions(-)
+
+diff --git a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+index 06a605ff4670..d823a12190c0 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+@@ -1130,12 +1130,9 @@ CHECK_SIZE_AND_OFFSET(ipc_perm, uid);
+ #ifndef __GLIBC_PREREQ
+ #define __GLIBC_PREREQ(x, y) 0
+ #endif
+-#if (!defined(__aarch64__) || !SANITIZER_LINUX || __GLIBC_PREREQ (2, 21)) && \
+-    !defined(__arm__)
+-/* On aarch64 glibc 2.20 and earlier provided incorrect mode field.  */
+-/* On Arm glibc 2.31 and later provide a different mode field, this field is
+-   never used by libsanitizer so we can simply ignore this assert for all glibc
+-   versions.  */
++#if !SANITIZER_LINUX || __GLIBC_PREREQ (2, 31)
++/* glibc 2.30 and earlier provided 16-bit mode field instead of 32-bit
++   on many architectures.  */
+ CHECK_SIZE_AND_OFFSET(ipc_perm, mode);
+ #endif
+ 
+diff --git a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h
+index 73af92af1e8f..6a673a7c9959 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h
+@@ -211,20 +211,13 @@ namespace __sanitizer {
+     unsigned long __unused1;
+     unsigned long __unused2;
+ #elif defined(__sparc__)
+-# if defined(__arch64__)
+     unsigned mode;
+-    unsigned short __pad1;
+-# else
+-    unsigned short __pad1;
+-    unsigned short mode;
+     unsigned short __pad2;
+-# endif
+     unsigned short __seq;
+     unsigned long long __unused1;
+     unsigned long long __unused2;
+ #else
+-    unsigned short mode;
+-    unsigned short __pad1;
++    unsigned int mode;
+     unsigned short __seq;
+     unsigned short __pad2;
+ #if defined(__x86_64__) && !defined(_LP64)
diff --git a/packages/gcc/glibc-2.31-libsanitizer-2-gcc-7.patch b/packages/gcc/glibc-2.31-libsanitizer-2-gcc-7.patch
new file mode 100644
index 0000000000000000000000000000000000000000..07cbb3fdb4960cdf7212746c376b2a9e0cbdfbd8
--- /dev/null
+++ b/packages/gcc/glibc-2.31-libsanitizer-2-gcc-7.patch
@@ -0,0 +1,69 @@
+From 75003cdd23c310ec385344e8040d490e8dd6d2be Mon Sep 17 00:00:00 2001
+From: Jakub Jelinek <jakub@redhat.com>
+Date: Fri, 20 Dec 2019 17:58:35 +0100
+Subject: [PATCH] backport: re PR sanitizer/92154 (new glibc breaks arm
+ bootstrap due to libsanitizer)
+
+	Backported from mainline
+	2019-11-26  Jakub Jelinek  <jakub@redhat.com>
+	Backported for version 7.1.0 <= gcc <= 7.4.0
+	2020-06-05  John L. Jolly  <john.jolly@gmail.com>
+
+	PR sanitizer/92154
+	* sanitizer_common/sanitizer_platform_limits_posix.h: Cherry-pick
+	llvm-project revision 947f9692440836dcb8d88b74b69dd379d85974ce.
+	* sanitizer_common/sanitizer_platform_limits_posix.cc: Likewise.
+
+From-SVN: r279653
+---
+ libsanitizer/ChangeLog                            | 10 ++++++++++
+ .../sanitizer_platform_limits_posix.cc            |  9 +++------
+ .../sanitizer_platform_limits_posix.h             | 15 +--------------
+ 3 files changed, 14 insertions(+), 20 deletions(-)
+
+diff --git a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+index 06a605ff4670..d823a12190c0 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+@@ -1156,12 +1156,9 @@ CHECK_SIZE_AND_OFFSET(ipc_perm, uid);
+ CHECK_SIZE_AND_OFFSET(ipc_perm, gid);
+ CHECK_SIZE_AND_OFFSET(ipc_perm, cuid);
+ CHECK_SIZE_AND_OFFSET(ipc_perm, cgid);
+-#if (!defined(__aarch64__) || !SANITIZER_LINUX || __GLIBC_PREREQ (2, 21)) && \
+-    !defined(__arm__)
+-/* On aarch64 glibc 2.20 and earlier provided incorrect mode field.  */
+-/* On Arm glibc 2.31 and later provide a different mode field, this field is
+-   never used by libsanitizer so we can simply ignore this assert for all glibc
+-   versions.  */
++#if !SANITIZER_LINUX || __GLIBC_PREREQ (2, 31)
++/* glibc 2.30 and earlier provided 16-bit mode field instead of 32-bit
++   on many architectures.  */
+ CHECK_SIZE_AND_OFFSET(ipc_perm, mode);
+ #endif
+ 
+diff --git a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h
+index 73af92af1e8f..6a673a7c9959 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h
+@@ -211,20 +211,13 @@ namespace __sanitizer {
+     unsigned long __unused1;
+     unsigned long __unused2;
+ #elif defined(__sparc__)
+-# if defined(__arch64__)
+     unsigned mode;
+-    unsigned short __pad1;
+-# else
+-    unsigned short __pad1;
+-    unsigned short mode;
+     unsigned short __pad2;
+-# endif
+     unsigned short __seq;
+     unsigned long long __unused1;
+     unsigned long long __unused2;
+ #else
+-    unsigned short mode;
+-    unsigned short __pad1;
++    unsigned int mode;
+     unsigned short __seq;
+     unsigned short __pad2;
+ #if defined(__x86_64__) && !defined(_LP64)
diff --git a/packages/gcc/glibc-2.31-libsanitizer-2.patch b/packages/gcc/glibc-2.31-libsanitizer-2.patch
new file mode 100644
index 0000000000000000000000000000000000000000..75234436e8e8d250fbbe266c8fa5c240715f0181
--- /dev/null
+++ b/packages/gcc/glibc-2.31-libsanitizer-2.patch
@@ -0,0 +1,73 @@
+From 75003cdd23c310ec385344e8040d490e8dd6d2be Mon Sep 17 00:00:00 2001
+From: Jakub Jelinek <jakub@redhat.com>
+Date: Fri, 20 Dec 2019 17:58:35 +0100
+Subject: [PATCH] backport: re PR sanitizer/92154 (new glibc breaks arm
+ bootstrap due to libsanitizer)
+
+	Backported from mainline
+	2019-11-26  Jakub Jelinek  <jakub@redhat.com>
+
+	PR sanitizer/92154
+	* sanitizer_common/sanitizer_platform_limits_posix.h: Cherry-pick
+	llvm-project revision 947f9692440836dcb8d88b74b69dd379d85974ce.
+	* sanitizer_common/sanitizer_platform_limits_posix.cc: Likewise.
+
+From-SVN: r279653
+---
+ libsanitizer/ChangeLog                            | 10 ++++++++++
+ .../sanitizer_platform_limits_posix.cc            |  9 +++------
+ .../sanitizer_platform_limits_posix.h             | 15 +--------------
+ 3 files changed, 14 insertions(+), 20 deletions(-)
+
+diff --git a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+index 06a605ff4670..d823a12190c0 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+@@ -1156,12 +1156,9 @@ CHECK_SIZE_AND_OFFSET(ipc_perm, uid);
+ CHECK_SIZE_AND_OFFSET(ipc_perm, gid);
+ CHECK_SIZE_AND_OFFSET(ipc_perm, cuid);
+ CHECK_SIZE_AND_OFFSET(ipc_perm, cgid);
+-#if (!defined(__aarch64__) || !SANITIZER_LINUX || __GLIBC_PREREQ (2, 21)) && \
+-    !defined(__arm__)
+-/* On aarch64 glibc 2.20 and earlier provided incorrect mode field.  */
+-/* On Arm glibc 2.31 and later provide a different mode field, this field is
+-   never used by libsanitizer so we can simply ignore this assert for all glibc
+-   versions.  */
++#if !SANITIZER_LINUX || __GLIBC_PREREQ (2, 31)
++/* glibc 2.30 and earlier provided 16-bit mode field instead of 32-bit
++   on many architectures.  */
+ CHECK_SIZE_AND_OFFSET(ipc_perm, mode);
+ #endif
+ 
+diff --git a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h
+index 73af92af1e8f..6a673a7c9959 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h
+@@ -211,26 +211,13 @@ namespace __sanitizer {
+     u64 __unused1;
+     u64 __unused2;
+ #elif defined(__sparc__)
+-#if defined(__arch64__)
+     unsigned mode;
+-    unsigned short __pad1;
+-#else
+-    unsigned short __pad1;
+-    unsigned short mode;
+     unsigned short __pad2;
+-#endif
+     unsigned short __seq;
+     unsigned long long __unused1;
+     unsigned long long __unused2;
+-#elif defined(__mips__) || defined(__aarch64__) || defined(__s390x__)
+-    unsigned int mode;
+-    unsigned short __seq;
+-    unsigned short __pad1;
+-    unsigned long __unused1;
+-    unsigned long __unused2;
+ #else
+-    unsigned short mode;
+-    unsigned short __pad1;
++    unsigned int mode;
+     unsigned short __seq;
+     unsigned short __pad2;
+ #if defined(__x86_64__) && !defined(_LP64)
diff --git a/packages/gcc/glibc-2.31-libsanitizer-3-gcc-5.patch b/packages/gcc/glibc-2.31-libsanitizer-3-gcc-5.patch
new file mode 100644
index 0000000000000000000000000000000000000000..e1df265aa392963d8828df5747938e51545faeca
--- /dev/null
+++ b/packages/gcc/glibc-2.31-libsanitizer-3-gcc-5.patch
@@ -0,0 +1,81 @@
+diff -ru a/libsanitizer/sanitizer_common/sanitizer_common_interceptors_ioctl.inc b/libsanitizer/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
+--- a/libsanitizer/sanitizer_common/sanitizer_common_interceptors_ioctl.inc	2014-09-23 17:59:53.000000000 +0000
++++ b/libsanitizer/sanitizer_common/sanitizer_common_interceptors_ioctl.inc	2021-10-30 19:48:38.690007561 +0000
+@@ -358,15 +358,6 @@
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+   // _(SIOCDEVPLIP, WRITE, struct_ifreq_sz); // the same as EQL_ENSLAVE
+-  _(CYGETDEFTHRESH, WRITE, sizeof(int));
+-  _(CYGETDEFTIMEOUT, WRITE, sizeof(int));
+-  _(CYGETMON, WRITE, struct_cyclades_monitor_sz);
+-  _(CYGETTHRESH, WRITE, sizeof(int));
+-  _(CYGETTIMEOUT, WRITE, sizeof(int));
+-  _(CYSETDEFTHRESH, NONE, 0);
+-  _(CYSETDEFTIMEOUT, NONE, 0);
+-  _(CYSETTHRESH, NONE, 0);
+-  _(CYSETTIMEOUT, NONE, 0);
+   _(EQL_EMANCIPATE, WRITE, struct_ifreq_sz);
+   _(EQL_ENSLAVE, WRITE, struct_ifreq_sz);
+   _(EQL_GETMASTRCFG, WRITE, struct_ifreq_sz);
+diff -ru a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc	2021-10-30 19:40:51.805824323 +0000
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc	2021-10-30 19:51:13.640403192 +0000
+@@ -143,7 +143,6 @@
+ #include <sys/statvfs.h>
+ #include <sys/timex.h>
+ #include <sys/user.h>
+-#include <linux/cyclades.h>
+ #include <linux/if_eql.h>
+ #include <linux/if_plip.h>
+ #include <linux/lp.h>
+@@ -392,7 +391,6 @@
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+   unsigned struct_ax25_parms_struct_sz = sizeof(struct ax25_parms_struct);
+-  unsigned struct_cyclades_monitor_sz = sizeof(struct cyclades_monitor);
+ #if EV_VERSION > (0x010000)
+   unsigned struct_input_keymap_entry_sz = sizeof(struct input_keymap_entry);
+ #else
+@@ -759,15 +757,6 @@
+ #endif  // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+-  unsigned IOCTL_CYGETDEFTHRESH = CYGETDEFTHRESH;
+-  unsigned IOCTL_CYGETDEFTIMEOUT = CYGETDEFTIMEOUT;
+-  unsigned IOCTL_CYGETMON = CYGETMON;
+-  unsigned IOCTL_CYGETTHRESH = CYGETTHRESH;
+-  unsigned IOCTL_CYGETTIMEOUT = CYGETTIMEOUT;
+-  unsigned IOCTL_CYSETDEFTHRESH = CYSETDEFTHRESH;
+-  unsigned IOCTL_CYSETDEFTIMEOUT = CYSETDEFTIMEOUT;
+-  unsigned IOCTL_CYSETTHRESH = CYSETTHRESH;
+-  unsigned IOCTL_CYSETTIMEOUT = CYSETTIMEOUT;
+   unsigned IOCTL_EQL_EMANCIPATE = EQL_EMANCIPATE;
+   unsigned IOCTL_EQL_ENSLAVE = EQL_ENSLAVE;
+   unsigned IOCTL_EQL_GETMASTRCFG = EQL_GETMASTRCFG;
+diff -ru a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h	2021-10-30 19:40:51.698824053 +0000
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h	2021-10-30 19:51:39.680469814 +0000
+@@ -875,7 +875,6 @@
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+   extern unsigned struct_ax25_parms_struct_sz;
+-  extern unsigned struct_cyclades_monitor_sz;
+   extern unsigned struct_input_keymap_entry_sz;
+   extern unsigned struct_ipx_config_data_sz;
+   extern unsigned struct_kbdiacrs_sz;
+@@ -1220,15 +1219,6 @@
+ #endif  // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+-  extern unsigned IOCTL_CYGETDEFTHRESH;
+-  extern unsigned IOCTL_CYGETDEFTIMEOUT;
+-  extern unsigned IOCTL_CYGETMON;
+-  extern unsigned IOCTL_CYGETTHRESH;
+-  extern unsigned IOCTL_CYGETTIMEOUT;
+-  extern unsigned IOCTL_CYSETDEFTHRESH;
+-  extern unsigned IOCTL_CYSETDEFTIMEOUT;
+-  extern unsigned IOCTL_CYSETTHRESH;
+-  extern unsigned IOCTL_CYSETTIMEOUT;
+   extern unsigned IOCTL_EQL_EMANCIPATE;
+   extern unsigned IOCTL_EQL_ENSLAVE;
+   extern unsigned IOCTL_EQL_GETMASTRCFG;
diff --git a/packages/gcc/glibc-2.36-libsanitizer-gcc-10-12.patch b/packages/gcc/glibc-2.36-libsanitizer-gcc-10-12.patch
new file mode 100644
index 0000000000000000000000000000000000000000..90df6b048612978c62947ed57ac8c7a40508ba73
--- /dev/null
+++ b/packages/gcc/glibc-2.36-libsanitizer-gcc-10-12.patch
@@ -0,0 +1,27 @@
+diff --git a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cpp b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cpp
+index badf6a401cc..b43733033a6 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cpp
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cpp
+@@ -72,7 +72,6 @@
+ #include <sys/vt.h>
+ #include <linux/cdrom.h>
+ #include <linux/fd.h>
+-#include <linux/fs.h>
+ #include <linux/hdreg.h>
+ #include <linux/input.h>
+ #include <linux/ioctl.h>
+@@ -822,10 +821,10 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned IOCTL_EVIOCGPROP = IOCTL_NOT_PRESENT;
+   unsigned IOCTL_EVIOCSKEYCODE_V2 = IOCTL_NOT_PRESENT;
+ #endif
+-  unsigned IOCTL_FS_IOC_GETFLAGS = FS_IOC_GETFLAGS;
+-  unsigned IOCTL_FS_IOC_GETVERSION = FS_IOC_GETVERSION;
+-  unsigned IOCTL_FS_IOC_SETFLAGS = FS_IOC_SETFLAGS;
+-  unsigned IOCTL_FS_IOC_SETVERSION = FS_IOC_SETVERSION;
++  unsigned IOCTL_FS_IOC_GETFLAGS = _IOR('f', 1, long);
++  unsigned IOCTL_FS_IOC_GETVERSION = _IOR('v', 1, long);
++  unsigned IOCTL_FS_IOC_SETFLAGS = _IOW('f', 2, long);
++  unsigned IOCTL_FS_IOC_SETVERSION = _IOW('v', 2, long);
+   unsigned IOCTL_GIO_CMAP = GIO_CMAP;
+   unsigned IOCTL_GIO_FONT = GIO_FONT;
+   unsigned IOCTL_GIO_UNIMAP = GIO_UNIMAP;
diff --git a/packages/gcc/glibc-2.36-libsanitizer-gcc-5-9.patch b/packages/gcc/glibc-2.36-libsanitizer-gcc-5-9.patch
new file mode 100644
index 0000000000000000000000000000000000000000..2cd2bc4e5b393398bd935121e06f390b36551957
--- /dev/null
+++ b/packages/gcc/glibc-2.36-libsanitizer-gcc-5-9.patch
@@ -0,0 +1,27 @@
+diff --git a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+index e8fce8a02..5122baa46 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+@@ -65,7 +65,6 @@
+ #include <sys/vt.h>
+ #include <linux/cdrom.h>
+ #include <linux/fd.h>
+-#include <linux/fs.h>
+ #include <linux/hdreg.h>
+ #include <linux/input.h>
+ #include <linux/ioctl.h>
+@@ -846,10 +845,10 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+   unsigned IOCTL_EVIOCGPROP = IOCTL_NOT_PRESENT;
+   unsigned IOCTL_EVIOCSKEYCODE_V2 = IOCTL_NOT_PRESENT;
+ #endif
+-  unsigned IOCTL_FS_IOC_GETFLAGS = FS_IOC_GETFLAGS;
+-  unsigned IOCTL_FS_IOC_GETVERSION = FS_IOC_GETVERSION;
+-  unsigned IOCTL_FS_IOC_SETFLAGS = FS_IOC_SETFLAGS;
+-  unsigned IOCTL_FS_IOC_SETVERSION = FS_IOC_SETVERSION;
++  unsigned IOCTL_FS_IOC_GETFLAGS = _IOR('f', 1, long);
++  unsigned IOCTL_FS_IOC_GETVERSION = _IOR('v', 1, long);
++  unsigned IOCTL_FS_IOC_SETFLAGS = _IOW('f', 2, long);
++  unsigned IOCTL_FS_IOC_SETVERSION = _IOW('v', 2, long);
+   unsigned IOCTL_GIO_CMAP = GIO_CMAP;
+   unsigned IOCTL_GIO_FONT = GIO_FONT;
+   unsigned IOCTL_GIO_UNIMAP = GIO_UNIMAP;
diff --git a/packages/gcc/package.py b/packages/gcc/package.py
new file mode 100644
index 0000000000000000000000000000000000000000..68f52b46f3a3c6b2093e0ad180c7ecb2d4dce01f
--- /dev/null
+++ b/packages/gcc/package.py
@@ -0,0 +1,1091 @@
+# Copyright 2013-2023 Lawrence Livermore National Security, LLC and other
+# Spack Project Developers. See the top-level COPYRIGHT file for details.
+#
+# SPDX-License-Identifier: (Apache-2.0 OR MIT)
+import glob
+import itertools
+import os
+import re
+import sys
+
+from archspec.cpu import UnsupportedMicroarchitecture
+
+import llnl.util.tty as tty
+from llnl.util.lang import classproperty
+
+import spack.platforms
+import spack.util.executable
+from spack.build_environment import dso_suffix
+from spack.operating_systems.mac_os import macos_sdk_path, macos_version
+from spack.package import *
+
+
+class Gcc(AutotoolsPackage, GNUMirrorPackage):
+    """The GNU Compiler Collection includes front ends for C, C++, Objective-C,
+    Fortran, Ada, and Go, as well as libraries for these languages."""
+
+    homepage = "https://gcc.gnu.org"
+    gnu_mirror_path = "gcc/gcc-9.2.0/gcc-9.2.0.tar.xz"
+    git = "git://gcc.gnu.org/git/gcc.git"
+    list_url = "https://ftp.gnu.org/gnu/gcc/"
+    list_depth = 1
+    keep_werror = "all"
+
+    maintainers("michaelkuhn", "alalazo")
+
+    version("master", branch="master")
+
+    version("13.1.0", sha256="61d684f0aa5e76ac6585ad8898a2427aade8979ed5e7f85492286c4dfc13ee86")
+
+    version("12.3.0", sha256="949a5d4f99e786421a93b532b22ffab5578de7321369975b91aec97adfda8c3b")
+    version("12.2.0", sha256="e549cf9cf3594a00e27b6589d4322d70e0720cdd213f39beb4181e06926230ff")
+    version("12.1.0", sha256="62fd634889f31c02b64af2c468f064b47ad1ca78411c45abe6ac4b5f8dd19c7b")
+
+    version("11.3.0", sha256="b47cf2818691f5b1e21df2bb38c795fac2cfbd640ede2d0a5e1c89e338a3ac39")
+    version("11.2.0", sha256="d08edc536b54c372a1010ff6619dd274c0f1603aa49212ba20f7aa2cda36fa8b")
+    version("11.1.0", sha256="4c4a6fb8a8396059241c2e674b85b351c26a5d678274007f076957afa1cc9ddf")
+
+    version("10.4.0", sha256="c9297d5bcd7cb43f3dfc2fed5389e948c9312fd962ef6a4ce455cff963ebe4f1")
+    version("10.3.0", sha256="64f404c1a650f27fc33da242e1f2df54952e3963a49e06e73f6940f3223ac344")
+    version("10.2.0", sha256="b8dd4368bb9c7f0b98188317ee0254dd8cc99d1e3a18d0ff146c855fe16c1d8c")
+    version("10.1.0", sha256="b6898a23844b656f1b68691c5c012036c2e694ac4b53a8918d4712ad876e7ea2")
+
+    version("9.5.0", sha256="27769f64ef1d4cd5e2be8682c0c93f9887983e6cfd1a927ce5a0a2915a95cf8f")
+    version("9.4.0", sha256="c95da32f440378d7751dd95533186f7fc05ceb4fb65eb5b85234e6299eb9838e")
+    version("9.3.0", sha256="71e197867611f6054aa1119b13a0c0abac12834765fe2d81f35ac57f84f742d1")
+    version("9.2.0", sha256="ea6ef08f121239da5695f76c9b33637a118dcf63e24164422231917fa61fb206")
+    version("9.1.0", sha256="79a66834e96a6050d8fe78db2c3b32fb285b230b855d0a66288235bc04b327a0")
+
+    version("8.5.0", sha256="d308841a511bb830a6100397b0042db24ce11f642dab6ea6ee44842e5325ed50")
+    version("8.4.0", sha256="e30a6e52d10e1f27ed55104ad233c30bd1e99cfb5ff98ab022dc941edd1b2dd4")
+    version("8.3.0", sha256="64baadfe6cc0f4947a84cb12d7f0dfaf45bb58b7e92461639596c21e02d97d2c")
+    version("8.2.0", sha256="196c3c04ba2613f893283977e6011b2345d1cd1af9abeac58e916b1aab3e0080")
+    version("8.1.0", sha256="1d1866f992626e61349a1ccd0b8d5253816222cdc13390dcfaa74b093aa2b153")
+
+    version("7.5.0", sha256="b81946e7f01f90528a1f7352ab08cc602b9ccc05d4e44da4bd501c5a189ee661")
+    version("7.4.0", sha256="eddde28d04f334aec1604456e536416549e9b1aa137fc69204e65eb0c009fe51")
+    version("7.3.0", sha256="832ca6ae04636adbb430e865a1451adf6979ab44ca1c8374f61fba65645ce15c")
+    version("7.2.0", sha256="1cf7adf8ff4b5aa49041c8734bbcf1ad18cc4c94d0029aae0f4e48841088479a")
+    version("7.1.0", sha256="8a8136c235f64c6fef69cac0d73a46a1a09bb250776a050aec8f9fc880bebc17")
+
+    version("6.5.0", sha256="7ef1796ce497e89479183702635b14bb7a46b53249209a5e0f999bebf4740945")
+    version("6.4.0", sha256="850bf21eafdfe5cd5f6827148184c08c4a0852a37ccf36ce69855334d2c914d4")
+    version("6.3.0", sha256="f06ae7f3f790fbf0f018f6d40e844451e6bc3b7bc96e128e63b09825c1f8b29f")
+    version("6.2.0", sha256="9944589fc722d3e66308c0ce5257788ebd7872982a718aa2516123940671b7c5")
+    version("6.1.0", sha256="09c4c85cabebb971b1de732a0219609f93fc0af5f86f6e437fd8d7f832f1a351")
+
+    version("5.5.0", sha256="530cea139d82fe542b358961130c69cfde8b3d14556370b65823d2f91f0ced87")
+    version("5.4.0", sha256="608df76dec2d34de6558249d8af4cbee21eceddbcb580d666f7a5a583ca3303a")
+    version("5.3.0", sha256="b84f5592e9218b73dbae612b5253035a7b34a9a1f7688d2e1bfaaf7267d5c4db")
+    version("5.2.0", sha256="5f835b04b5f7dd4f4d2dc96190ec1621b8d89f2dc6f638f9f8bc1b1014ba8cad")
+    version("5.1.0", sha256="b7dafdf89cbb0e20333dbf5b5349319ae06e3d1a30bf3515b5488f7e89dca5ad")
+
+    version("4.9.4", sha256="6c11d292cd01b294f9f84c9a59c230d80e9e4a47e5c6355f046bb36d4f358092")
+    version("4.9.3", sha256="2332b2a5a321b57508b9031354a8503af6fdfb868b8c1748d33028d100a8b67e")
+    version("4.9.2", sha256="2020c98295856aa13fda0f2f3a4794490757fc24bcca918d52cc8b4917b972dd")
+    version("4.9.1", sha256="d334781a124ada6f38e63b545e2a3b8c2183049515a1abab6d513f109f1d717e")
+    version("4.8.5", sha256="22fb1e7e0f68a63cee631d85b20461d1ea6bda162f03096350e38c8d427ecf23")
+    version("4.8.4", sha256="4a80aa23798b8e9b5793494b8c976b39b8d9aa2e53cd5ed5534aff662a7f8695")
+    version("4.7.4", sha256="92e61c6dc3a0a449e62d72a38185fda550168a86702dea07125ebd3ec3996282")
+    version("4.6.4", sha256="35af16afa0b67af9b8eb15cafb76d2bc5f568540552522f5dc2c88dd45d977e8")
+    version("4.5.4", sha256="eef3f0456db8c3d992cbb51d5d32558190bc14f3bc19383dd93acc27acc6befc")
+
+    # We specifically do not add 'all' variant here because:
+    # (i) Ada, D, Go, Jit, and Objective-C++ are not default languages.
+    # In that respect, the name 'all' is rather misleading.
+    # (ii) Languages other than c,c++,fortran are prone to configure bug in GCC
+    # For example, 'java' appears to ignore custom location of zlib
+    # (iii) meaning of 'all' changes with GCC version, i.e. 'java' is not part
+    # of gcc7. Correctly specifying conflicts() and depends_on() in such a
+    # case is a PITA.
+    #
+    # Also note that some languages get enabled by the configure scripts even if not listed in the
+    # arguments. For example, c++ is enabled when the bootstrapping is enabled and lto is enabled
+    # when the link time optimization support is enabled.
+    variant(
+        "languages",
+        default="c,c++,fortran",
+        values=(
+            "ada",
+            "brig",
+            "c",
+            "c++",
+            "d",
+            "fortran",
+            "go",
+            "java",
+            "jit",
+            "lto",
+            "objc",
+            "obj-c++",
+        ),
+        multi=True,
+        description="Compilers and runtime libraries to build",
+    )
+    variant("binutils", default=False, description="Build via binutils")
+    variant(
+        "piclibs", default=False, description="Build PIC versions of libgfortran.a and libstdc++.a"
+    )
+    variant("strip", default=False, description="Strip executables to reduce installation size")
+    variant("nvptx", default=False, description="Target nvptx offloading to NVIDIA GPUs")
+    variant("bootstrap", default=True, description="Enable 3-stage bootstrap")
+    variant(
+        "graphite", default=False, description="Enable Graphite loop optimizations (requires ISL)"
+    )
+    variant(
+        "build_type",
+        default="RelWithDebInfo",
+        values=("Debug", "Release", "RelWithDebInfo", "MinSizeRel"),
+        description="CMake-like build type. "
+        "Debug: -O0 -g; Release: -O3; "
+        "RelWithDebInfo: -O2 -g; MinSizeRel: -Os",
+    )
+    variant(
+        "profiled",
+        default=False,
+        description="Use Profile Guided Optimization",
+        when="+bootstrap %gcc",
+    )
+
+    depends_on("flex", type="build", when="@master")
+
+    # https://gcc.gnu.org/install/prerequisites.html
+    depends_on("gmp@4.3.2:")
+    # mawk is not sufficient for go support
+    depends_on("gawk@3.1.5:", type="build")
+    depends_on("texinfo@4.7:", type="build")
+    depends_on("libtool", type="build")
+    # dependencies required for git versions
+    depends_on("m4@1.4.6:", when="@master", type="build")
+    depends_on("automake@1.15.1:", when="@master", type="build")
+    depends_on("autoconf@2.69:", when="@master", type="build")
+
+    depends_on("gmake@3.80:", type="build")
+    depends_on("perl@5", type="build")
+
+    # GCC 7.3 does not compile with newer releases on some platforms, see
+    #   https://github.com/spack/spack/issues/6902#issuecomment-433030376
+    depends_on("mpfr@2.4.2:3.1.6", when="@:9.9")
+    depends_on("mpfr@3.1.0:", when="@10:")
+    depends_on("mpc@1.0.1:", when="@4.5:")
+    # Already released GCC versions do not support any newer version of ISL
+    #   GCC 5.4 https://github.com/spack/spack/issues/6902#issuecomment-433072097
+    #   GCC 7.3 https://github.com/spack/spack/issues/6902#issuecomment-433030376
+    #   GCC 9+  https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86724
+    with when("+graphite"):
+        depends_on("isl@0.14", when="@5.0:5.2")
+        depends_on("isl@0.15", when="@5.3:5.9")
+        depends_on("isl@0.15:0.18", when="@6:8.9")
+        depends_on("isl@0.15:0.20", when="@9:9.9")
+        depends_on("isl@0.15:", when="@10:")
+
+    depends_on("zlib", when="@6:")
+    depends_on("zstd", when="@10:")
+    depends_on("diffutils", type="build")
+    depends_on("iconv", when="platform=darwin")
+    depends_on("gnat", when="languages=ada")
+    depends_on(
+        "binutils+gas+ld+plugins~libiberty", when="+binutils", type=("build", "link", "run")
+    )
+    depends_on("zip", type="build", when="languages=java")
+
+    # The server is sometimes a bit slow to respond
+    timeout = {"timeout": 60}
+
+    # TODO: integrate these libraries.
+    # depends_on('ppl')
+    # depends_on('cloog')
+
+    # https://gcc.gnu.org/install/test.html
+    depends_on("dejagnu@1.4.4", type="test")
+    depends_on("expect", type="test")
+    depends_on("tcl", type="test")
+    depends_on("autogen@5.5.4:", type="test")
+    depends_on("guile@1.4.1:", type="test")
+
+    # See https://go.dev/doc/install/gccgo#Releases
+    with when("languages=go"):
+        provides("go-or-gccgo-bootstrap@:1.0", when="@4.7.1:")
+        provides("go-or-gccgo-bootstrap@:1.2", when="@4.9:")
+        provides("go-or-gccgo-bootstrap@:1.4", when="@5:")
+        provides("go-or-gccgo-bootstrap@:1.6.1", when="@6:")
+        provides("go-or-gccgo-bootstrap@:1.8.1", when="@7:")
+        provides("go-or-gccgo-bootstrap@:1.10.1", when="@8:")
+        provides("go-or-gccgo-bootstrap@:1.12.2", when="@9:")
+        provides("go-or-gccgo-bootstrap@:1.14.6", when="@10:")
+        provides("go-or-gccgo-bootstrap@1.16.3:1.16.5", when="@11:")
+
+        provides("golang@:1.0", when="@4.7.1:")
+        provides("golang@:1.2", when="@4.9:")
+        provides("golang@:1.4", when="@5:")
+        provides("golang@:1.6.1", when="@6:")
+        provides("golang@:1.8.1", when="@7:")
+        provides("golang@:1.10.1", when="@8:")
+        provides("golang@:1.12.2", when="@9:")
+        provides("golang@:1.14.6", when="@10:")
+        provides("golang@1.16.3:1.16.5", when="@11:")
+
+        # GCC 4.7.1 added full support for the Go 1.x programming language.
+        conflicts("@:4.7.0")
+
+        # Go is not supported on macOS
+        conflicts("platform=darwin", msg="GCC cannot build Go support on MacOS")
+
+    # For a list of valid languages for a specific release,
+    # run the following command in the GCC source directory:
+    #    $ grep ^language= gcc/*/config-lang.in
+    # See https://gcc.gnu.org/install/configure.html
+
+    # Support for processing BRIG 1.0 files was added in GCC 7
+    # BRIG is a binary format for HSAIL:
+    # (Heterogeneous System Architecture Intermediate Language).
+    # See https://gcc.gnu.org/gcc-7/changes.html
+    conflicts("languages=brig", when="@:6")
+
+    # BRIG does not seem to be supported on macOS
+    conflicts("languages=brig", when="platform=darwin")
+
+    # GCC 4.8 added a 'c' language. I'm sure C was always built,
+    # but this is the first version that accepts 'c' as a valid language.
+    conflicts("languages=c", when="@:4.7")
+
+    # The GCC Java frontend and associated libjava runtime library
+    # have been removed from GCC as of GCC 7.
+    # See https://gcc.gnu.org/gcc-7/changes.html
+    conflicts("languages=java", when="@7:")
+
+    # GCC 5 added the ability to build GCC as a Just-In-Time compiler.
+    # See https://gcc.gnu.org/gcc-5/changes.html
+    conflicts("languages=jit", when="@:4")
+
+    with when("languages=d"):
+        # The very first version of GDC that became part of GCC already supported version 2.076 of
+        # the language and runtime.
+        # See https://wiki.dlang.org/GDC#Status
+        provides("D@2")
+
+        # Support for the D programming language has been added to GCC 9.
+        # See https://gcc.gnu.org/gcc-9/changes.html#d
+        conflicts("@:8", msg="support for D has been added in GCC 9.1")
+
+        # Versions of GDC prior to 12 can be built with an ISO C++11 compiler. Starting version 12,
+        # the D frontend requires a working GDC. Moreover, it is strongly recommended to use an
+        # older version of GDC to build GDC.
+        # See https://gcc.gnu.org/install/prerequisites.html#GDC-prerequisite
+        with when("@12:"):
+            # All versions starting 12 have to be built GCC:
+            requires("%gcc")
+
+            # And it has to be GCC older than the version we build:
+            vv = ["11", "12.1.0", "12.2.0"]
+            for prev_v, curr_v in zip(vv, vv[1:]):
+                conflicts(
+                    "%gcc@{0}:".format(curr_v),
+                    when="@{0}".format(curr_v),
+                    msg="'gcc@{0} languages=d' requires '%gcc@:{1}' "
+                    "with the D language support".format(curr_v, prev_v),
+                )
+
+            # In principle, it is possible to have GDC even with GCC 5.
+            # See https://github.com/D-Programming-GDC/gdc
+            # We, however, require at least the oldest version that officially supports GDC. It is
+            # also a good opportunity to tell the users that they need a working GDC:
+            conflicts(
+                "%gcc@:8",
+                msg="'gcc@12: languages=d' requires '%gcc@9:' with the D language support",
+            )
+
+    with when("+nvptx"):
+        depends_on("cuda")
+        resource(
+            name="newlib",
+            url="ftp://sourceware.org/pub/newlib/newlib-3.0.0.20180831.tar.gz",
+            sha256="3ad3664f227357df15ff34e954bfd9f501009a647667cd307bf0658aefd6eb5b",
+            destination="newlibsource",
+            fetch_options=timeout,
+        )
+        # nvptx-tools does not seem to work as a dependency,
+        # but does fine when the source is inside the gcc build directory
+        # nvptx-tools doesn't have any releases, so grabbing the last commit
+        resource(
+            name="nvptx-tools",
+            git="https://github.com/MentorEmbedded/nvptx-tools",
+            commit="d0524fbdc86dfca068db5a21cc78ac255b335be5",
+        )
+        # NVPTX offloading supported in 7 and later by limited languages
+        conflicts("@:6", msg="NVPTX only supported in gcc 7 and above")
+        conflicts("languages=ada")
+        conflicts("languages=brig")
+        conflicts("languages=go")
+        conflicts("languages=java")
+        conflicts("languages=jit")
+        conflicts("languages=objc")
+        conflicts("languages=obj-c++")
+        conflicts("languages=d")
+        # NVPTX build disables bootstrap
+        conflicts("+bootstrap")
+
+    # Binutils can't build ld on macOS
+    conflicts("+binutils", when="platform=darwin")
+
+    # Bootstrap comparison failure:
+    #   see https://github.com/spack/spack/issues/23296
+    #   https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100340
+    #   on XCode 12.5
+    conflicts("+bootstrap", when="@:11.1 %apple-clang@12.0.5")
+
+    # aarch64/M1 is supported in GCC 11.3-12.2
+    conflicts(
+        "@:11.2,12.3:",
+        when="target=aarch64: platform=darwin",
+        msg="Only GCC 11.3-12.2 support macOS M1 (aarch64)",
+    )
+
+    # Newer binutils than RHEL's is required to run `as` on some instructions
+    # generated by new GCC (see https://github.com/spack/spack/issues/12235)
+    conflicts("~binutils", when="@7: os=rhel6", msg="New GCC cannot use system assembler on RHEL6")
+    # Ditto for RHEL7/8: OpenBLAS uses flags which the RHEL system-binutils don't have:
+    # https://github.com/xianyi/OpenBLAS/issues/3805#issuecomment-1319878852
+    conflicts(
+        "~binutils", when="@10: os=rhel7", msg="gcc: Add +binutils - preinstalled as might be old"
+    )
+    conflicts(
+        "~binutils", when="@10: os=rhel8", msg="gcc: Add +binutils - preinstalled as might be old"
+    )
+
+    # GCC 11 requires GCC 4.8 or later (https://gcc.gnu.org/gcc-11/changes.html)
+    conflicts("%gcc@:4.7", when="@11:")
+
+    # https://github.com/iains/gcc-12-branch/issues/6
+    conflicts("@:12", when="%apple-clang@14:14.0")
+
+    if sys.platform == "darwin":
+        # Fix parallel build on APFS filesystem
+        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81797
+        if macos_version() >= Version("10.13"):
+            patch("darwin/apfs.patch", when="@5.5.0,6.1:6.4,7.1:7.3")
+            # from homebrew via macports
+            # https://trac.macports.org/ticket/56502#no1
+            # see also: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=83531
+            patch("darwin/headers-10.13-fix.patch", when="@5.5.0")
+        if macos_version() >= Version("10.14"):
+            # Fix system headers for Mojave SDK:
+            # https://github.com/Homebrew/homebrew-core/pull/39041
+            patch(
+                "https://raw.githubusercontent.com/Homebrew/formula-patches/b8b8e65e/gcc/8.3.0-xcode-bug-_Atomic-fix.patch",
+                sha256="33ee92bf678586357ee8ab9d2faddf807e671ad37b97afdd102d5d153d03ca84",
+                when="@6:8.3",
+            )
+        if macos_version() >= Version("10.15"):
+            # Fix system headers for Catalina SDK
+            # (otherwise __OSX_AVAILABLE_STARTING ends up undefined)
+            patch(
+                "https://raw.githubusercontent.com/Homebrew/formula-patches/b8b8e65e/gcc/9.2.0-catalina.patch",
+                sha256="0b8d14a7f3c6a2f0d2498526e86e088926671b5da50a554ffa6b7f73ac4f132b",
+                when="@9.2.0",
+            )
+
+            # See https://raw.githubusercontent.com/Homebrew/homebrew-core/3b7db4457ac64a31e3bbffc54b04c4bd824a4a4a/Formula/gcc.rb
+            patch(
+                "https://github.com/iains/gcc-darwin-arm64/commit/20f61faaed3b335d792e38892d826054d2ac9f15.patch?full_index=1",
+                sha256="c0605179a856ca046d093c13cea4d2e024809ec2ad4bf3708543fc3d2e60504b",
+                when="@11.2.0",
+            )
+
+        # Apple M1 support, created from branch of Darwin maintainer for GCC:
+        # https://github.com/iains/gcc-11-branch
+        patch(
+            "https://raw.githubusercontent.com/Homebrew/formula-patches/22dec3fc/gcc/gcc-11.3.0-arm.diff",
+            sha256="e02006b7ec917cc1390645d95735a6a866caed0dfe506d5bef742f7862cab218",
+            when="@11.3.0 target=aarch64:",
+        )
+        # https://github.com/iains/gcc-12-branch
+        patch(
+            "https://raw.githubusercontent.com/Homebrew/formula-patches/76677f2b/gcc/gcc-12.1.0-arm.diff",
+            sha256="a000f1d9cb1dd98c7c4ef00df31435cd5d712d2f9d037ddc044f8bf82a16cf35",
+            when="@12.1.0 target=aarch64:",
+        )
+        patch(
+            "https://raw.githubusercontent.com/Homebrew/formula-patches/1d184289/gcc/gcc-12.2.0-arm.diff",
+            sha256="a7843b5c6bf1401e40c20c72af69c8f6fc9754ae980bb4a5f0540220b3dcb62d",
+            when="@12.2.0 target=aarch64:",
+        )
+        conflicts("+bootstrap", when="@11.3.0 target=aarch64:")
+
+        # Use -headerpad_max_install_names in the build,
+        # otherwise updated load commands won't fit in the Mach-O header.
+        # This is needed because `gcc` avoids the superenv shim.
+        patch("darwin/gcc-7.1.0-headerpad.patch", when="@5:11.2")
+        patch("darwin/gcc-6.1.0-jit.patch", when="@5:7")
+        patch("darwin/gcc-4.9.patch1", when="@4.9.0:4.9.3")
+        patch("darwin/gcc-4.9.patch2", when="@4.9.0:4.9.3")
+
+        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=92061
+        patch("darwin/clang13.patch", when="@:11.1 %apple-clang@13")
+
+    patch("piclibs.patch", when="+piclibs")
+    patch("gcc-backport.patch", when="@4.7:4.9.3,5:5.3")
+
+    # Backport libsanitizer patch for glibc >= 2.31 and 5.3.0 <= gcc <= 9.2.0
+    # https://bugs.gentoo.org/708346
+    patch("glibc-2.31-libsanitizer-1.patch", when="@7.1.0:7.5.0,8.1.0:8.3.0,9.0.0:9.2.0")
+    patch("glibc-2.31-libsanitizer-1-gcc-6.patch", when="@5.3.0:5.5.0,6.1.0:6.5.0")
+    patch("glibc-2.31-libsanitizer-2.patch", when="@8.1.0:8.3.0,9.0.0:9.2.0")
+    patch("glibc-2.31-libsanitizer-2-gcc-6.patch", when="@5.3.0:5.5.0,6.1.0:6.5.0")
+    patch("glibc-2.31-libsanitizer-2-gcc-7.patch", when="@7.1.0:7.5.0")
+    patch(
+        "patch-2b40941d23b1570cdd90083b58fa0f66aa58c86e.patch",
+        when="@6.5.0,7.4.0:7.5.0,8.2.0:9.3.0",
+    )
+    patch("patch-745dae5923aba02982563481d75a21595df22ff8.patch", when="@10.1.0:10.3.0,11.1.0")
+
+    # Backport libsanitizer patch for glibc >= 2.36
+    # https://reviews.llvm.org/D129471
+    patch("glibc-2.36-libsanitizer-gcc-5-9.patch", when="@5.1:5.5,6.1:6.5,7.1:7.5,8.1:8.5,9.1:9.5")
+    patch("glibc-2.36-libsanitizer-gcc-10-12.patch", when="@10.1:10.4,11.1:11.3,12.1.0")
+
+    # Older versions do not compile with newer versions of glibc
+    # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81712
+    patch("ucontext_t.patch", when="@4.9,5.1:5.4,6.1:6.4,7.1")
+    patch("ucontext_t-java.patch", when="@4.9,5.1:5.4,6.1:6.4 languages=java")
+    # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81066
+    patch("stack_t-4.9.patch", when="@4.9")
+    patch("stack_t.patch", when="@5.1:5.4,6.1:6.4,7.1")
+    # https://bugs.busybox.net/show_bug.cgi?id=10061
+    patch("signal.patch", when="@4.9,5.1:5.4")
+    # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85835
+    patch("sys_ustat.h.patch", when="@5.0:6.4,7.0:7.3,8.1")
+    patch("sys_ustat-4.9.patch", when="@4.9")
+
+    # this patch removes cylades support from gcc-5 and allows gcc-5 to be built
+    # with newer glibc versions.
+    patch("glibc-2.31-libsanitizer-3-gcc-5.patch", when="@5.3.0:5.5.0")
+
+    # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95005
+    patch("zstd.patch", when="@10")
+
+    # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100102
+    patch("patch-fc930b3010bd0de899a3da3209eab20664ddb703.patch", when="@10.1:10.3")
+    patch("patch-f1feb74046e0feb0596b93bbb822fae02940a90e.patch", when="@11.1")
+
+    # libstdc++: Fix inconsistent noexcept-specific for valarray begin/end
+    patch(
+        "https://github.com/gcc-mirror/gcc/commit/423cd47cfc9640ba3d6811b780e8a0b94b704dcb.patch?full_index=1",
+        sha256="0d136226eb07bc43f1b15284f48bd252e3748a0426b5d7ac9084ebc406e15490",
+        when="@9.5.0:11.2",
+    )
+
+    build_directory = "spack-build"
+
+    @classproperty
+    def executables(cls):
+        names = [r"gcc", r"[^\w]?g\+\+", r"gfortran", r"gdc", r"gccgo"]
+        suffixes = [r"", r"-mp-\d+\.\d", r"-\d+\.\d", r"-\d+", r"\d\d"]
+        return [r"".join(x) for x in itertools.product(names, suffixes)]
+
+    @classmethod
+    def filter_detected_exes(cls, prefix, exes_in_prefix):
+        result = []
+        for exe in exes_in_prefix:
+            # On systems like Ubuntu we might get multiple executables
+            # with the string "gcc" in them. See:
+            # https://helpmanual.io/packages/apt/gcc/
+            basename = os.path.basename(exe)
+            substring_to_be_filtered = [
+                "c99-gcc",
+                "c89-gcc",
+                "-nm",
+                "-ar",
+                "ranlib",
+                "clang",  # clang++ matches g++ -> clan[g++]
+            ]
+            if any(x in basename for x in substring_to_be_filtered):
+                continue
+            # Filter out links in favor of real executables on
+            # all systems but Cray
+            host_platform = str(spack.platforms.host())
+            if os.path.islink(exe) and host_platform != "cray":
+                continue
+
+            result.append(exe)
+
+        return result
+
+    @classmethod
+    def determine_version(cls, exe):
+        try:
+            output = spack.compiler.get_compiler_version_output(exe, "--version")
+        except Exception:
+            output = ""
+        # Apple's gcc is actually apple clang, so skip it.
+        # Users can add it manually to compilers.yaml at their own risk.
+        if "Apple" in output:
+            return None
+
+        version_regex = re.compile(r"([\d\.]+)")
+        for vargs in ("-dumpfullversion", "-dumpversion"):
+            try:
+                output = spack.compiler.get_compiler_version_output(exe, vargs)
+                match = version_regex.search(output)
+                if match:
+                    return match.group(1)
+            except spack.util.executable.ProcessError:
+                pass
+            except Exception as e:
+                tty.debug(e)
+
+        return None
+
+    @classmethod
+    def determine_variants(cls, exes, version_str):
+        languages, compilers = set(), {}
+        # There are often at least two copies (not symlinks) of each compiler executable in the
+        # same directory: one with a canonical name, e.g. "gfortran", and another one with the
+        # target prefix, e.g. "x86_64-pc-linux-gnu-gfortran". There also might be a copy of "gcc"
+        # with the version suffix, e.g. "x86_64-pc-linux-gnu-gcc-6.3.0". To ensure the consistency
+        # of values in the "compilers" dictionary (i.e. we prefer all of them to reference copies
+        # with canonical names if possible), we iterate over the executables in the reversed sorted
+        # order:
+        for exe in sorted(exes, reverse=True):
+            basename = os.path.basename(exe)
+            if "g++" in basename:
+                languages.add("c++")
+                compilers["cxx"] = exe
+            elif "gfortran" in basename:
+                languages.add("fortran")
+                compilers["fortran"] = exe
+            elif "gcc" in basename:
+                languages.add("c")
+                compilers["c"] = exe
+            elif "gccgo" in basename:
+                languages.add("go")
+                compilers["go"] = exe
+            elif "gdc" in basename:
+                languages.add("d")
+                compilers["d"] = exe
+        variant_str = "languages={0}".format(",".join(languages))
+        return variant_str, {"compilers": compilers}
+
+    @classmethod
+    def validate_detected_spec(cls, spec, extra_attributes):
+        # For GCC 'compilers' is a mandatory attribute
+        msg = 'the extra attribute "compilers" must be set for ' 'the detected spec "{0}"'.format(
+            spec
+        )
+        assert "compilers" in extra_attributes, msg
+
+        compilers = extra_attributes["compilers"]
+        for constraint, key in {
+            "languages=c": "c",
+            "languages=c++": "cxx",
+            "languages=d": "d",
+            "languages=fortran": "fortran",
+        }.items():
+            if spec.satisfies(constraint):
+                msg = "{0} not in {1}"
+                assert key in compilers, msg.format(key, spec)
+
+    @property
+    def cc(self):
+        msg = "cannot retrieve C compiler [spec is not concrete]"
+        assert self.spec.concrete, msg
+        if self.spec.external:
+            return self.spec.extra_attributes["compilers"].get("c", None)
+        result = None
+        if "languages=c" in self.spec:
+            result = str(self.spec.prefix.bin.gcc)
+        return result
+
+    @property
+    def cxx(self):
+        msg = "cannot retrieve C++ compiler [spec is not concrete]"
+        assert self.spec.concrete, msg
+        if self.spec.external:
+            return self.spec.extra_attributes["compilers"].get("cxx", None)
+        result = None
+        if "languages=c++" in self.spec:
+            result = os.path.join(self.spec.prefix.bin, "g++")
+        return result
+
+    @property
+    def fortran(self):
+        msg = "cannot retrieve Fortran compiler [spec is not concrete]"
+        assert self.spec.concrete, msg
+        if self.spec.external:
+            return self.spec.extra_attributes["compilers"].get("fortran", None)
+        result = None
+        if "languages=fortran" in self.spec:
+            result = str(self.spec.prefix.bin.gfortran)
+        return result
+
+    def url_for_version(self, version):
+        # This function will be called when trying to fetch from url, before
+        # mirrors are tried. It takes care of modifying the suffix of gnu
+        # mirror path so that Spack will also look for the correct file in
+        # the mirrors
+        if (version < Version("6.4.0") and version != Version("5.5.0")) or version == Version(
+            "7.1.0"
+        ):
+            self.gnu_mirror_path = self.gnu_mirror_path.replace("xz", "bz2")
+        return super(Gcc, self).url_for_version(version)
+
+    def patch(self):
+        spec = self.spec
+        prefix = self.spec.prefix
+
+        # Fix a standard header file for OS X Yosemite that
+        # is GCC incompatible by replacing non-GCC compliant macros
+        if "yosemite" in spec.architecture:
+            if os.path.isfile("/usr/include/dispatch/object.h"):
+                new_dispatch_dir = join_path(prefix, "include", "dispatch")
+                mkdirp(new_dispatch_dir)
+                new_header = join_path(new_dispatch_dir, "object.h")
+                install("/usr/include/dispatch/object.h", new_header)
+                filter_file(
+                    r"typedef void \(\^dispatch_block_t\)\(void\)",
+                    "typedef void* dispatch_block_t",
+                    new_header,
+                )
+
+        # Use installed libz
+        if self.version >= Version("6"):
+            filter_file("@zlibdir@", "-L{0}".format(spec["zlib"].prefix.lib), "gcc/Makefile.in")
+            filter_file(
+                "@zlibinc@", "-I{0}".format(spec["zlib"].prefix.include), "gcc/Makefile.in"
+            )
+
+        if spec.satisfies("+nvptx"):
+            # backport of 383400a6078d upstream to allow support of cuda@11:
+            filter_file(
+                '#define ASM_SPEC "%{misa=*:-m %*}"',
+                '#define ASM_SPEC "%{misa=*:-m %*; :-m sm_35}"',
+                "gcc/config/nvptx/nvptx.h",
+                string=True,
+            )
+            filter_file(
+                "Target RejectNegative ToLower Joined "
+                "Enum(ptx_isa) Var(ptx_isa_option) Init(PTX_ISA_SM30)",
+                "Target RejectNegative ToLower Joined "
+                "Enum(ptx_isa) Var(ptx_isa_option) Init(PTX_ISA_SM35)",
+                "gcc/config/nvptx/nvptx.opt",
+                string=True,
+            )
+        self.build_optimization_config()
+
+    def get_common_target_flags(self, spec):
+        """Get the right (but pessimistic) architecture specific flags supported by
+        both host gcc and to-be-built gcc. For example: gcc@7 %gcc@12 target=znver3
+        should pick -march=znver1, since that's what gcc@7 supports."""
+        archs = [spec.target] + spec.target.ancestors
+        for arch in archs:
+            try:
+                return arch.optimization_flags("gcc", spec.version)
+            except UnsupportedMicroarchitecture:
+                pass
+        # no arch specific flags in common, unlikely to happen.
+        return ""
+
+    def build_optimization_config(self):
+        """Write a config/spack.mk file with sensible optimization flags, taking into
+        account bootstrapping subtleties."""
+        build_type_flags = {
+            "Debug": "-O0 -g",
+            "Release": "-O3",
+            "RelWithDebInfo": "-O2 -g",
+            "MinSizeRel": "-Os",
+        }
+
+        # Generic optimization flags.
+        flags = build_type_flags[self.spec.variants["build_type"].value]
+
+        # Pessimistic target specific flags. For example, when building
+        # gcc@11 %gcc@7 on znver3, Spack will fix the target to znver1 during
+        # concretization, so we'll stick to that. The other way around however can
+        # result in compilation errors, when gcc@7 is built with gcc@11, and znver3
+        # is taken as a the target, which gcc@7 doesn't support.
+        # Note we're not adding this for aarch64 because of
+        # https://github.com/spack/spack/issues/31184
+        if "+bootstrap %gcc" in self.spec and self.spec.target.family != "aarch64":
+            flags += " " + self.get_common_target_flags(self.spec)
+
+        if "+bootstrap" in self.spec:
+            variables = ["BOOT_CFLAGS", "CFLAGS_FOR_TARGET", "CXXFLAGS_FOR_TARGET"]
+        else:
+            variables = ["CFLAGS", "CXXFLAGS"]
+
+        # Redefine a few variables without losing other defaults:
+        # BOOT_CFLAGS = $(filter-out -O% -g%, $(BOOT_CFLAGS)) -O3
+        # This makes sure that build_type=Release is really -O3, not -O3 -g.
+        fmt_string = "{} := $(filter-out -O% -g%, $({})) {}\n"
+        with open("config/spack.mk", "w") as f:
+            for var in variables:
+                f.write(fmt_string.format(var, var, flags))
+            # Improve the build time for stage 2 a bit by enabling -O1 in stage 1.
+            # Note: this is ignored under ~bootstrap.
+            f.write("STAGE1_CFLAGS += -O1\n")
+
+    # https://gcc.gnu.org/install/configure.html
+    def configure_args(self):
+        spec = self.spec
+
+        # Generic options to compile GCC
+        options = [
+            # Distributor options
+            "--with-pkgversion=Spack GCC",
+            "--with-bugurl=https://github.com/spack/spack/issues",
+            # Xcode 10 dropped 32-bit support
+            "--disable-multilib",
+            "--enable-languages={0}".format(",".join(spec.variants["languages"].value)),
+            # Drop gettext dependency
+            "--disable-nls",
+        ]
+
+        # Avoid excessive realpath/stat calls for every system header
+        # by making -fno-canonical-system-headers the default.
+        if self.version >= Version("4.8.0"):
+            options.append("--disable-canonical-system-headers")
+
+        # Use installed libz
+        if self.version >= Version("6"):
+            options.append("--with-system-zlib")
+
+        if "zstd" in spec:
+            options.append("--with-zstd-include={0}".format(spec["zstd"].headers.directories[0]))
+            options.append("--with-zstd-lib={0}".format(spec["zstd"].libs.directories[0]))
+
+        # Enabling language "jit" requires --enable-host-shared.
+        if "languages=jit" in spec:
+            options.append("--enable-host-shared")
+
+        # Binutils
+        if spec.satisfies("+binutils"):
+            binutils = spec["binutils"].prefix.bin
+            options.extend(
+                [
+                    "--with-gnu-ld",
+                    "--with-ld=" + binutils.ld,
+                    "--with-gnu-as",
+                    "--with-as=" + binutils.join("as"),
+                ]
+            )
+
+        # enable_bootstrap
+        if spec.satisfies("+bootstrap"):
+            options.extend(["--enable-bootstrap"])
+        else:
+            options.extend(["--disable-bootstrap"])
+
+        # Configure include and lib directories explicitly for these
+        # dependencies since the short GCC option assumes that libraries
+        # are installed in "/lib" which might not be true on all OS
+        # (see #10842)
+        #
+        # More info at: https://gcc.gnu.org/install/configure.html
+        for dep_str in ("mpfr", "gmp", "mpc", "isl"):
+            if dep_str not in spec:
+                options.append("--without-{0}".format(dep_str))
+                continue
+
+            dep_spec = spec[dep_str]
+            include_dir = dep_spec.headers.directories[0]
+            lib_dir = dep_spec.libs.directories[0]
+            options.extend(
+                [
+                    "--with-{0}-include={1}".format(dep_str, include_dir),
+                    "--with-{0}-lib={1}".format(dep_str, lib_dir),
+                ]
+            )
+
+        # nvptx-none offloading for host compiler
+        if spec.satisfies("+nvptx"):
+            options.extend(
+                [
+                    "--enable-offload-targets=nvptx-none",
+                    "--with-cuda-driver-include={0}".format(spec["cuda"].prefix.include),
+                    "--with-cuda-driver-lib={0}".format(spec["cuda"].libs.directories[0]),
+                    "--disable-bootstrap",
+                    "--disable-multilib",
+                ]
+            )
+
+        if sys.platform == "darwin":
+            options.extend(
+                [
+                    "--with-native-system-header-dir=/usr/include",
+                    "--with-sysroot={0}".format(macos_sdk_path()),
+                    "--with-libiconv-prefix={0}".format(spec["iconv"].prefix),
+                ]
+            )
+
+        # enable appropriate bootstrapping flags
+        stage1_ldflags = str(self.rpath_args)
+        boot_ldflags = stage1_ldflags + " -static-libstdc++ -static-libgcc"
+        options.append("--with-stage1-ldflags=" + stage1_ldflags)
+        options.append("--with-boot-ldflags=" + boot_ldflags)
+        options.append("--with-build-config=spack")
+
+        if "languages=d" in spec:
+            # Phobos is the standard library for the D Programming Language. The documentation says
+            # that on some targets, 'libphobos' is not enabled by default, but compiles and works
+            # if '--enable-libphobos' is used. Specifics are documented for affected targets.
+            # See https://gcc.gnu.org/install/prerequisites.html#GDC-prerequisite
+            # Unfortunately, it is unclear where exactly the aforementioned specifics are
+            # documented but GDC seems to be unusable without the library, therefore we enable it
+            # explicitly:
+            options.append("--enable-libphobos")
+            if spec.satisfies("@12:"):
+                options.append("GDC={0}".format(self.detect_gdc()))
+
+        return options
+
+    # run configure/make/make(install) for the nvptx-none target
+    # before running the host compiler phases
+    @run_before("configure")
+    def nvptx_install(self):
+        spec = self.spec
+        prefix = self.prefix
+
+        if not spec.satisfies("+nvptx"):
+            return
+
+        # config.guess returns the host triple, e.g. "x86_64-pc-linux-gnu"
+        guess = Executable("./config.guess")
+        targetguess = guess(output=str).rstrip("\n")
+
+        options = getattr(self, "configure_flag_args", [])
+        options += ["--prefix={0}".format(prefix)]
+
+        options += [
+            "--with-cuda-driver-include={0}".format(spec["cuda"].prefix.include),
+            "--with-cuda-driver-lib={0}".format(spec["cuda"].libs.directories[0]),
+        ]
+
+        with working_dir("nvptx-tools"):
+            configure = Executable("./configure")
+            configure(*options)
+            make()
+            make("install")
+
+        pattern = join_path(self.stage.source_path, "newlibsource", "*")
+        files = glob.glob(pattern)
+
+        if files:
+            symlink(join_path(files[0], "newlib"), "newlib")
+
+        # self.build_directory = 'spack-build-nvptx'
+        with working_dir("spack-build-nvptx", create=True):
+            options = [
+                "--prefix={0}".format(prefix),
+                "--enable-languages={0}".format(",".join(spec.variants["languages"].value)),
+                "--with-mpfr={0}".format(spec["mpfr"].prefix),
+                "--with-gmp={0}".format(spec["gmp"].prefix),
+                "--target=nvptx-none",
+                "--with-build-time-tools={0}".format(join_path(prefix, "nvptx-none", "bin")),
+                "--enable-as-accelerator-for={0}".format(targetguess),
+                "--disable-sjlj-exceptions",
+                "--enable-newlib-io-long-long",
+            ]
+
+            configure = Executable("../configure")
+            configure(*options)
+            make()
+            make("install")
+
+    @property
+    def build_targets(self):
+        if "+profiled" in self.spec:
+            return ["profiledbootstrap"]
+        return []
+
+    @property
+    def install_targets(self):
+        if "+strip" in self.spec:
+            return ["install-strip"]
+        return ["install"]
+
+    @property
+    def spec_dir(self):
+        # e.g. lib/gcc/x86_64-unknown-linux-gnu/4.9.2
+        spec_dir = glob.glob("{0}/gcc/*/*".format(self.prefix.lib))
+        return spec_dir[0] if spec_dir else None
+
+    @run_after("install")
+    def write_rpath_specs(self):
+        """Generate a spec file so the linker adds a rpath to the libs
+        the compiler used to build the executable.
+
+        .. caution::
+
+           The custom spec file by default with *always* pass ``-Wl,-rpath
+           ...`` to the linker, which will cause the linker to *ignore* the
+           value of ``LD_RUN_PATH``, which otherwise would be saved to the
+           binary as the default rpath. See the mitigation below for how to
+           temporarily disable this behavior.
+
+        Structure the specs file so that users can define a custom spec file
+        to suppress the spack-linked rpaths to facilitate rpath adjustment
+        for relocatable binaries. The custom spec file
+        :file:`{norpath}.spec` will have a single
+        line followed by two blanks lines::
+
+            *link_libgcc_rpath:
+
+
+
+        It can be passed to the GCC linker using the argument
+        ``--specs=norpath.spec`` to disable the automatic rpath and restore
+        the behavior of ``LD_RUN_PATH``."""
+        if not self.spec_dir:
+            tty.warn(
+                "Could not install specs for {0}.".format(self.spec.format("{name}{@version}"))
+            )
+            return
+
+        gcc = self.spec["gcc"].command
+        lines = gcc("-dumpspecs", output=str).splitlines(True)
+        specs_file = join_path(self.spec_dir, "specs")
+
+        # Save a backup
+        with open(specs_file + ".orig", "w") as out:
+            out.writelines(lines)
+
+        # Find which directories have shared libraries
+        rpath_libdirs = []
+        for dir in ["lib", "lib64"]:
+            libdir = join_path(self.prefix, dir)
+            if glob.glob(join_path(libdir, "*." + dso_suffix)):
+                rpath_libdirs.append(libdir)
+
+        if not rpath_libdirs:
+            # No shared libraries
+            tty.warn("No dynamic libraries found in lib/lib64")
+            return
+
+        # Overwrite the specs file
+        with open(specs_file, "w") as out:
+            for line in lines:
+                out.write(line)
+                if line.startswith("*link_libgcc:"):
+                    # Insert at start of line following link_libgcc, which gets
+                    # inserted into every call to the linker
+                    out.write("%(link_libgcc_rpath) ")
+
+            # Add easily-overridable rpath string at the end
+            out.write("*link_libgcc_rpath:\n")
+            out.write(" ".join("-rpath " + lib for lib in rpath_libdirs))
+            out.write("\n")
+        set_install_permissions(specs_file)
+        tty.info("Wrote new spec file to {0}".format(specs_file))
+
+    def setup_run_environment(self, env):
+        # Search prefix directory for possibly modified compiler names
+        from spack.compilers.gcc import Gcc as Compiler
+
+        # Get the contents of the installed binary directory
+        bin_path = self.spec.prefix.bin
+
+        if not os.path.isdir(bin_path):
+            return
+
+        bin_contents = os.listdir(bin_path)
+
+        # Find the first non-symlink compiler binary present for each language
+        for lang in ["cc", "cxx", "fc", "f77"]:
+            for filename, regexp in itertools.product(bin_contents, Compiler.search_regexps(lang)):
+                if not regexp.match(filename):
+                    continue
+
+                abspath = os.path.join(bin_path, filename)
+                if os.path.islink(abspath):
+                    continue
+
+                # Set the proper environment variable
+                env.set(lang.upper(), abspath)
+                # Stop searching filename/regex combos for this language
+                break
+
+    def detect_gdc(self):
+        """Detect and return the path to GDC that belongs to the same instance of GCC that is used
+        by self.compiler.
+
+        If the path cannot be detected, raise InstallError with recommendations for the users on
+        how to circumvent the problem.
+
+        Should be use only if self.spec.satisfies("@12: languages=d")
+        """
+        # Detect GCC package in the directory of the GCC compiler
+        # or in the $PATH if self.compiler.cc is not an absolute path:
+        from spack.detection import by_executable
+
+        compiler_dir = os.path.dirname(self.compiler.cc)
+        detected_packages = by_executable(
+            [self.__class__], path_hints=([compiler_dir] if os.path.isdir(compiler_dir) else None)
+        )
+
+        # We consider only packages that satisfy the following constraint:
+        required_spec = Spec("languages=c,c++,d")
+        candidate_specs = [
+            p.spec
+            for p in filter(
+                lambda p: p.spec.satisfies(required_spec), detected_packages.get(self.name, ())
+            )
+        ]
+
+        if candidate_specs:
+            # We now need to filter specs that match the compiler version:
+            compiler_spec = Spec(repr(self.compiler.spec))
+
+            # First, try to filter specs that satisfy the compiler spec:
+            new_candidate_specs = list(
+                filter(lambda s: s.satisfies(compiler_spec), candidate_specs)
+            )
+
+            # The compiler version might be more specific than what we can detect. For example, the
+            # user might have "gcc@10.2.1-sys" as the compiler spec in compilers.yaml. In that
+            # case, we end up with an empty list of candidates. To circumvent the problem, we try
+            # to filter specs that are satisfied by the compiler spec:
+            if not new_candidate_specs:
+                new_candidate_specs = list(
+                    filter(lambda s: compiler_spec.satisfies(s), candidate_specs)
+                )
+
+            candidate_specs = new_candidate_specs
+
+        error_nl = "\n    "  # see SpackError.__str__()
+
+        if not candidate_specs:
+            raise InstallError(
+                "Cannot detect GDC",
+                long_msg="Starting version 12, the D frontend requires a working GDC."
+                "{0}You can install it with Spack by running:"
+                "{0}{0}spack install gcc@9:11 languages=c,c++,d"
+                "{0}{0}Once that has finished, you will need to add it to your compilers.yaml file"
+                "{0}and use it to install this spec (i.e. {1} ...).".format(
+                    error_nl, self.spec.format("{name}{@version} {variants.languages}")
+                ),
+            )
+        elif len(candidate_specs) == 0:
+            return candidate_specs[0].extra_attributes["compilers"]["d"]
+        else:
+            # It is rather unlikely to end up here but let us try to resolve the ambiguity:
+            candidate_gdc = candidate_specs[0].extra_attributes["compilers"]["d"]
+            if all(
+                candidate_gdc == s.extra_attributes["compilers"]["d"] for s in candidate_specs[1:]
+            ):
+                # It does not matter which one we take if they are all the same:
+                return candidate_gdc
+            else:
+                raise InstallError(
+                    "Cannot resolve ambiguity when detecting GDC that belongs to "
+                    "%{0}".format(self.compiler.spec),
+                    long_msg="The candidates are:{0}{0}{1}{0}".format(
+                        error_nl,
+                        error_nl.join(
+                            "{0} (cc: {1})".format(
+                                s.extra_attributes["compilers"]["d"],
+                                s.extra_attributes["compilers"]["c"],
+                            )
+                            for s in candidate_specs
+                        ),
+                    ),
+                )
diff --git a/packages/gcc/patch-2b40941d23b1570cdd90083b58fa0f66aa58c86e.patch b/packages/gcc/patch-2b40941d23b1570cdd90083b58fa0f66aa58c86e.patch
new file mode 100644
index 0000000000000000000000000000000000000000..3d76c47b3c16e0a2ca2ea6d0d1093a84233843ce
--- /dev/null
+++ b/packages/gcc/patch-2b40941d23b1570cdd90083b58fa0f66aa58c86e.patch
@@ -0,0 +1,121 @@
+From 2b40941d23b1570cdd90083b58fa0f66aa58c86e Mon Sep 17 00:00:00 2001
+From: Tamar Christina <tamar.christina@arm.com>
+Date: Fri, 21 May 2021 12:16:56 +0100
+Subject: [PATCH] libsanitizer: Remove cyclades from libsanitizer
+
+The Linux kernel has removed the interface to cyclades from
+the latest kernel headers[1] due to them being orphaned for the
+past 13 years.
+
+libsanitizer uses this header when compiling against glibc, but
+glibcs itself doesn't seem to have any references to cyclades.
+
+Further more it seems that the driver is broken in the kernel and
+the firmware doesn't seem to be available anymore.
+
+As such since this is breaking the build of libsanitizer (and so the
+GCC bootstrap[2]) I propose to remove this.
+
+[1] https://lkml.org/lkml/2021/3/2/153
+[2] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100379
+
+libsanitizer/ChangeLog:
+
+	PR sanitizer/100379
+	* sanitizer_common/sanitizer_common_interceptors_ioctl.inc: Cherry-pick
+	llvm-project revision f7c5351552387bd43f6ca3631016d7f0dfe0f135.
+	* sanitizer_common/sanitizer_platform_limits_posix.cc: Likewise.
+	* sanitizer_common/sanitizer_platform_limits_posix.h: Likewise.
+---
+ .../sanitizer_common_interceptors_ioctl.inc           |  9 ---------
+ .../sanitizer_platform_limits_posix.cc                | 11 -----------
+ .../sanitizer_platform_limits_posix.h                 | 10 ----------
+ 3 files changed, 30 deletions(-)
+
+diff --git a/libsanitizer/sanitizer_common/sanitizer_common_interceptors_ioctl.inc b/libsanitizer/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
+index 5408ea17c59..7a9cd3f5968 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
++++ b/libsanitizer/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
+@@ -365,15 +365,6 @@ static void ioctl_table_fill() {
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+   // _(SIOCDEVPLIP, WRITE, struct_ifreq_sz); // the same as EQL_ENSLAVE
+-  _(CYGETDEFTHRESH, WRITE, sizeof(int));
+-  _(CYGETDEFTIMEOUT, WRITE, sizeof(int));
+-  _(CYGETMON, WRITE, struct_cyclades_monitor_sz);
+-  _(CYGETTHRESH, WRITE, sizeof(int));
+-  _(CYGETTIMEOUT, WRITE, sizeof(int));
+-  _(CYSETDEFTHRESH, NONE, 0);
+-  _(CYSETDEFTIMEOUT, NONE, 0);
+-  _(CYSETTHRESH, NONE, 0);
+-  _(CYSETTIMEOUT, NONE, 0);
+   _(EQL_EMANCIPATE, WRITE, struct_ifreq_sz);
+   _(EQL_ENSLAVE, WRITE, struct_ifreq_sz);
+   _(EQL_GETMASTRCFG, WRITE, struct_ifreq_sz);
+diff --git a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+index d823a12190c..e8fce8a0287 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+@@ -157,7 +157,6 @@ typedef struct user_fpregs elf_fpregset_t;
+ # include <sys/procfs.h>
+ #endif
+ #include <sys/user.h>
+-#include <linux/cyclades.h>
+ #include <linux/if_eql.h>
+ #include <linux/if_plip.h>
+ #include <linux/lp.h>
+@@ -466,7 +465,6 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+   unsigned struct_ax25_parms_struct_sz = sizeof(struct ax25_parms_struct);
+-  unsigned struct_cyclades_monitor_sz = sizeof(struct cyclades_monitor);
+ #if EV_VERSION > (0x010000)
+   unsigned struct_input_keymap_entry_sz = sizeof(struct input_keymap_entry);
+ #else
+@@ -833,15 +831,6 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+-  unsigned IOCTL_CYGETDEFTHRESH = CYGETDEFTHRESH;
+-  unsigned IOCTL_CYGETDEFTIMEOUT = CYGETDEFTIMEOUT;
+-  unsigned IOCTL_CYGETMON = CYGETMON;
+-  unsigned IOCTL_CYGETTHRESH = CYGETTHRESH;
+-  unsigned IOCTL_CYGETTIMEOUT = CYGETTIMEOUT;
+-  unsigned IOCTL_CYSETDEFTHRESH = CYSETDEFTHRESH;
+-  unsigned IOCTL_CYSETDEFTIMEOUT = CYSETDEFTIMEOUT;
+-  unsigned IOCTL_CYSETTHRESH = CYSETTHRESH;
+-  unsigned IOCTL_CYSETTIMEOUT = CYSETTIMEOUT;
+   unsigned IOCTL_EQL_EMANCIPATE = EQL_EMANCIPATE;
+   unsigned IOCTL_EQL_ENSLAVE = EQL_ENSLAVE;
+   unsigned IOCTL_EQL_GETMASTRCFG = EQL_GETMASTRCFG;
+diff --git a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h
+index 6a673a7c995..f921bf2b5b5 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h
+@@ -1040,7 +1040,6 @@ struct __sanitizer_cookie_io_functions_t {
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+   extern unsigned struct_ax25_parms_struct_sz;
+-  extern unsigned struct_cyclades_monitor_sz;
+   extern unsigned struct_input_keymap_entry_sz;
+   extern unsigned struct_ipx_config_data_sz;
+   extern unsigned struct_kbdiacrs_sz;
+@@ -1385,15 +1384,6 @@ struct __sanitizer_cookie_io_functions_t {
+ #endif  // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+-  extern unsigned IOCTL_CYGETDEFTHRESH;
+-  extern unsigned IOCTL_CYGETDEFTIMEOUT;
+-  extern unsigned IOCTL_CYGETMON;
+-  extern unsigned IOCTL_CYGETTHRESH;
+-  extern unsigned IOCTL_CYGETTIMEOUT;
+-  extern unsigned IOCTL_CYSETDEFTHRESH;
+-  extern unsigned IOCTL_CYSETDEFTIMEOUT;
+-  extern unsigned IOCTL_CYSETTHRESH;
+-  extern unsigned IOCTL_CYSETTIMEOUT;
+   extern unsigned IOCTL_EQL_EMANCIPATE;
+   extern unsigned IOCTL_EQL_ENSLAVE;
+   extern unsigned IOCTL_EQL_GETMASTRCFG;
+-- 
+2.31.1
+
diff --git a/packages/gcc/patch-745dae5923aba02982563481d75a21595df22ff8.patch b/packages/gcc/patch-745dae5923aba02982563481d75a21595df22ff8.patch
new file mode 100644
index 0000000000000000000000000000000000000000..57c51eb231123761590fe9a11bf478f6a357884b
--- /dev/null
+++ b/packages/gcc/patch-745dae5923aba02982563481d75a21595df22ff8.patch
@@ -0,0 +1,123 @@
+From 745dae5923aba02982563481d75a21595df22ff8 Mon Sep 17 00:00:00 2001
+From: Tamar Christina <tamar.christina@arm.com>
+Date: Fri, 21 May 2021 10:30:59 +0100
+Subject: [PATCH] libsanitizer: Remove cyclades from libsanitizer
+
+The Linux kernel has removed the interface to cyclades from
+the latest kernel headers[1] due to them being orphaned for the
+past 13 years.
+
+libsanitizer uses this header when compiling against glibc, but
+glibcs itself doesn't seem to have any references to cyclades.
+
+Further more it seems that the driver is broken in the kernel and
+the firmware doesn't seem to be available anymore.
+
+As such since this is breaking the build of libsanitizer (and so the
+GCC bootstrap[2]) I propose to remove this.
+
+[1] https://lkml.org/lkml/2021/3/2/153
+[2] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=100379
+
+(cherry picked from commit f7c5351552387bd43f6ca3631016d7f0dfe0f135)
+
+libsanitizer/ChangeLog:
+
+	PR sanitizer/100379
+	* sanitizer_common/sanitizer_common_interceptors_ioctl.inc: Cherry-pick
+	llvm-project revision f7c5351552387bd43f6ca3631016d7f0dfe0f135.
+	* sanitizer_common/sanitizer_platform_limits_posix.cpp: Likewise.
+	* sanitizer_common/sanitizer_platform_limits_posix.h: Likewise.
+---
+ .../sanitizer_common_interceptors_ioctl.inc           |  9 ---------
+ .../sanitizer_platform_limits_posix.cpp               | 11 -----------
+ .../sanitizer_platform_limits_posix.h                 | 10 ----------
+ 3 files changed, 30 deletions(-)
+
+diff --git a/libsanitizer/sanitizer_common/sanitizer_common_interceptors_ioctl.inc b/libsanitizer/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
+index 7f181258eab..b7da6598755 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
++++ b/libsanitizer/sanitizer_common/sanitizer_common_interceptors_ioctl.inc
+@@ -370,15 +370,6 @@ static void ioctl_table_fill() {
+ 
+ #if SANITIZER_GLIBC
+   // _(SIOCDEVPLIP, WRITE, struct_ifreq_sz); // the same as EQL_ENSLAVE
+-  _(CYGETDEFTHRESH, WRITE, sizeof(int));
+-  _(CYGETDEFTIMEOUT, WRITE, sizeof(int));
+-  _(CYGETMON, WRITE, struct_cyclades_monitor_sz);
+-  _(CYGETTHRESH, WRITE, sizeof(int));
+-  _(CYGETTIMEOUT, WRITE, sizeof(int));
+-  _(CYSETDEFTHRESH, NONE, 0);
+-  _(CYSETDEFTIMEOUT, NONE, 0);
+-  _(CYSETTHRESH, NONE, 0);
+-  _(CYSETTIMEOUT, NONE, 0);
+   _(EQL_EMANCIPATE, WRITE, struct_ifreq_sz);
+   _(EQL_ENSLAVE, WRITE, struct_ifreq_sz);
+   _(EQL_GETMASTRCFG, WRITE, struct_ifreq_sz);
+diff --git a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cpp b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cpp
+index 35a690cba5c..6e5c330b98e 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cpp
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cpp
+@@ -143,7 +143,6 @@ typedef struct user_fpregs elf_fpregset_t;
+ # include <sys/procfs.h>
+ #endif
+ #include <sys/user.h>
+-#include <linux/cyclades.h>
+ #include <linux/if_eql.h>
+ #include <linux/if_plip.h>
+ #include <linux/lp.h>
+@@ -460,7 +459,6 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+ 
+ #if SANITIZER_GLIBC
+   unsigned struct_ax25_parms_struct_sz = sizeof(struct ax25_parms_struct);
+-  unsigned struct_cyclades_monitor_sz = sizeof(struct cyclades_monitor);
+ #if EV_VERSION > (0x010000)
+   unsigned struct_input_keymap_entry_sz = sizeof(struct input_keymap_entry);
+ #else
+@@ -824,15 +822,6 @@ unsigned struct_ElfW_Phdr_sz = sizeof(Elf_Phdr);
+ #endif // SANITIZER_LINUX
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+-  unsigned IOCTL_CYGETDEFTHRESH = CYGETDEFTHRESH;
+-  unsigned IOCTL_CYGETDEFTIMEOUT = CYGETDEFTIMEOUT;
+-  unsigned IOCTL_CYGETMON = CYGETMON;
+-  unsigned IOCTL_CYGETTHRESH = CYGETTHRESH;
+-  unsigned IOCTL_CYGETTIMEOUT = CYGETTIMEOUT;
+-  unsigned IOCTL_CYSETDEFTHRESH = CYSETDEFTHRESH;
+-  unsigned IOCTL_CYSETDEFTIMEOUT = CYSETDEFTIMEOUT;
+-  unsigned IOCTL_CYSETTHRESH = CYSETTHRESH;
+-  unsigned IOCTL_CYSETTIMEOUT = CYSETTIMEOUT;
+   unsigned IOCTL_EQL_EMANCIPATE = EQL_EMANCIPATE;
+   unsigned IOCTL_EQL_ENSLAVE = EQL_ENSLAVE;
+   unsigned IOCTL_EQL_GETMASTRCFG = EQL_GETMASTRCFG;
+diff --git a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h
+index ad358eef8b7..cba41ba5494 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.h
+@@ -983,7 +983,6 @@ extern unsigned struct_vt_mode_sz;
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+ extern unsigned struct_ax25_parms_struct_sz;
+-extern unsigned struct_cyclades_monitor_sz;
+ extern unsigned struct_input_keymap_entry_sz;
+ extern unsigned struct_ipx_config_data_sz;
+ extern unsigned struct_kbdiacrs_sz;
+@@ -1328,15 +1327,6 @@ extern unsigned IOCTL_VT_WAITACTIVE;
+ #endif  // SANITIZER_LINUX
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+-extern unsigned IOCTL_CYGETDEFTHRESH;
+-extern unsigned IOCTL_CYGETDEFTIMEOUT;
+-extern unsigned IOCTL_CYGETMON;
+-extern unsigned IOCTL_CYGETTHRESH;
+-extern unsigned IOCTL_CYGETTIMEOUT;
+-extern unsigned IOCTL_CYSETDEFTHRESH;
+-extern unsigned IOCTL_CYSETDEFTIMEOUT;
+-extern unsigned IOCTL_CYSETTHRESH;
+-extern unsigned IOCTL_CYSETTIMEOUT;
+ extern unsigned IOCTL_EQL_EMANCIPATE;
+ extern unsigned IOCTL_EQL_ENSLAVE;
+ extern unsigned IOCTL_EQL_GETMASTRCFG;
+-- 
+2.31.1
+
diff --git a/packages/gcc/patch-f1feb74046e0feb0596b93bbb822fae02940a90e.patch b/packages/gcc/patch-f1feb74046e0feb0596b93bbb822fae02940a90e.patch
new file mode 100644
index 0000000000000000000000000000000000000000..2448be074828bbfc9b09dad4759b2c55d8168073
--- /dev/null
+++ b/packages/gcc/patch-f1feb74046e0feb0596b93bbb822fae02940a90e.patch
@@ -0,0 +1,133 @@
+From f1feb74046e0feb0596b93bbb822fae02940a90e Mon Sep 17 00:00:00 2001
+From: Patrick Palka <ppalka@redhat.com>
+Date: Fri, 4 Jun 2021 13:46:53 -0400
+Subject: [PATCH] c++: tsubst_function_decl and excess arg levels [PR100102]
+
+Here, when instantiating the dependent alias template
+duration::__is_harmonic with args={{T,U},{int}}, we find ourselves
+substituting the function decl _S_gcd.  Since we have more arg levels
+than _S_gcd has parm levels, an old special case in tsubst_function_decl
+causes us to unwantedly reduce args to its innermost level, yielding
+args={int}, which leads to a nonsensical substitution into the decl
+context and eventually a crash.
+
+The comment for this special case refers to three examples for which we
+ought to see more arg levels than parm levels here, but none of the
+examples actually demonstrate this.  In the first example, when
+defining S<int>::f(U) parms_depth is 2 and args_depth is 1, and
+later when instantiating say S<int>::f<char> both depths are 2.  In the
+second example, when substituting the template friend declaration
+parms_depth is 2 and args_depth is 1, and later when instantiating f
+both depths are 1.  Finally, the third example is invalid since we can't
+specialize a member template of an unspecialized class template like
+that.
+
+Given that this reduction code seems no longer relevant for its
+documented purpose and that it causes problems as in the PR, this patch
+just removes it.  Note that as far as bootstrap/regtest is concerned,
+this code is dead; the below two tests would be the first to reach it.
+
+	PR c++/100102
+
+gcc/cp/ChangeLog:
+
+	* pt.c (tsubst_function_decl): Remove old code for reducing
+	args when it has excess levels.
+
+gcc/testsuite/ChangeLog:
+
+	* g++.dg/cpp0x/alias-decl-72.C: New test.
+	* g++.dg/cpp0x/alias-decl-72a.C: New test.
+
+(cherry picked from commit 5357ab75dedef403b0eebf9277d61d1cbeb5898f)
+---
+ gcc/cp/pt.c                                 | 39 ---------------------
+ gcc/testsuite/g++.dg/cpp0x/alias-decl-72.C  |  9 +++++
+ gcc/testsuite/g++.dg/cpp0x/alias-decl-72a.C |  9 +++++
+ 3 files changed, 18 insertions(+), 39 deletions(-)
+ create mode 100644 gcc/testsuite/g++.dg/cpp0x/alias-decl-72.C
+ create mode 100644 gcc/testsuite/g++.dg/cpp0x/alias-decl-72a.C
+
+diff --git a/gcc/cp/pt.c b/gcc/cp/pt.c
+index 1434beb80f4..1761a902218 100644
+--- a/gcc/cp/pt.c
++++ b/gcc/cp/pt.c
+@@ -13954,45 +13954,6 @@ tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
+ 	  if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
+ 	    return spec;
+ 	}
+-
+-      /* We can see more levels of arguments than parameters if
+-	 there was a specialization of a member template, like
+-	 this:
+-
+-	 template <class T> struct S { template <class U> void f(); }
+-	 template <> template <class U> void S<int>::f(U);
+-
+-	 Here, we'll be substituting into the specialization,
+-	 because that's where we can find the code we actually
+-	 want to generate, but we'll have enough arguments for
+-	 the most general template.
+-
+-	 We also deal with the peculiar case:
+-
+-	 template <class T> struct S {
+-	   template <class U> friend void f();
+-	 };
+-	 template <class U> void f() {}
+-	 template S<int>;
+-	 template void f<double>();
+-
+-	 Here, the ARGS for the instantiation of will be {int,
+-	 double}.  But, we only need as many ARGS as there are
+-	 levels of template parameters in CODE_PATTERN.  We are
+-	 careful not to get fooled into reducing the ARGS in
+-	 situations like:
+-
+-	 template <class T> struct S { template <class U> void f(U); }
+-	 template <class T> template <> void S<T>::f(int) {}
+-
+-	 which we can spot because the pattern will be a
+-	 specialization in this case.  */
+-      int args_depth = TMPL_ARGS_DEPTH (args);
+-      int parms_depth =
+-	TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
+-
+-      if (args_depth > parms_depth && !DECL_TEMPLATE_SPECIALIZATION (t))
+-	args = get_innermost_template_args (args, parms_depth);
+     }
+   else
+     {
+diff --git a/gcc/testsuite/g++.dg/cpp0x/alias-decl-72.C b/gcc/testsuite/g++.dg/cpp0x/alias-decl-72.C
+new file mode 100644
+index 00000000000..8009756dcba
+--- /dev/null
++++ b/gcc/testsuite/g++.dg/cpp0x/alias-decl-72.C
+@@ -0,0 +1,9 @@
++// PR c++/100102
++// { dg-do compile { target c++11 } }
++
++template<int()> struct ratio;
++template<class T, class U> struct duration {
++  static constexpr int _S_gcd();
++  template<class> using __is_harmonic = ratio<_S_gcd>;
++  using type = __is_harmonic<int>;
++};
+diff --git a/gcc/testsuite/g++.dg/cpp0x/alias-decl-72a.C b/gcc/testsuite/g++.dg/cpp0x/alias-decl-72a.C
+new file mode 100644
+index 00000000000..a4443e18f9d
+--- /dev/null
++++ b/gcc/testsuite/g++.dg/cpp0x/alias-decl-72a.C
+@@ -0,0 +1,9 @@
++// PR c++/100102
++// { dg-do compile { target c++11 } }
++
++template<int> struct ratio;
++template<class T> struct duration {
++  static constexpr int _S_gcd();
++  template<class> using __is_harmonic = ratio<(duration::_S_gcd)()>;
++  using type = __is_harmonic<int>;
++};
+-- 
+2.31.1
+
diff --git a/packages/gcc/patch-fc930b3010bd0de899a3da3209eab20664ddb703.patch b/packages/gcc/patch-fc930b3010bd0de899a3da3209eab20664ddb703.patch
new file mode 100644
index 0000000000000000000000000000000000000000..27e5a2b5bf0f7268704ac920e1ee064673b9e3af
--- /dev/null
+++ b/packages/gcc/patch-fc930b3010bd0de899a3da3209eab20664ddb703.patch
@@ -0,0 +1,133 @@
+From fc930b3010bd0de899a3da3209eab20664ddb703 Mon Sep 17 00:00:00 2001
+From: Patrick Palka <ppalka@redhat.com>
+Date: Fri, 4 Jun 2021 13:46:53 -0400
+Subject: [PATCH] c++: tsubst_function_decl and excess arg levels [PR100102]
+
+Here, when instantiating the dependent alias template
+duration::__is_harmonic with args={{T,U},{int}}, we find ourselves
+substituting the function decl _S_gcd.  Since we have more arg levels
+than _S_gcd has parm levels, an old special case in tsubst_function_decl
+causes us to unwantedly reduce args to its innermost level, yielding
+args={int}, which leads to a nonsensical substitution into the decl
+context and eventually a crash.
+
+The comment for this special case refers to three examples for which we
+ought to see more arg levels than parm levels here, but none of the
+examples actually demonstrate this.  In the first example, when
+defining S<int>::f(U) parms_depth is 2 and args_depth is 1, and
+later when instantiating say S<int>::f<char> both depths are 2.  In the
+second example, when substituting the template friend declaration
+parms_depth is 2 and args_depth is 1, and later when instantiating f
+both depths are 1.  Finally, the third example is invalid since we can't
+specialize a member template of an unspecialized class template like
+that.
+
+Given that this reduction code seems no longer relevant for its
+documented purpose and that it causes problems as in the PR, this patch
+just removes it.  Note that as far as bootstrap/regtest is concerned,
+this code is dead; the below two tests would be the first to reach it.
+
+	PR c++/100102
+
+gcc/cp/ChangeLog:
+
+	* pt.c (tsubst_function_decl): Remove old code for reducing
+	args when it has excess levels.
+
+gcc/testsuite/ChangeLog:
+
+	* g++.dg/cpp0x/alias-decl-72.C: New test.
+	* g++.dg/cpp0x/alias-decl-72a.C: New test.
+
+(cherry picked from commit 5357ab75dedef403b0eebf9277d61d1cbeb5898f)
+---
+ gcc/cp/pt.c                                 | 39 ---------------------
+ gcc/testsuite/g++.dg/cpp0x/alias-decl-72.C  |  9 +++++
+ gcc/testsuite/g++.dg/cpp0x/alias-decl-72a.C |  9 +++++
+ 3 files changed, 18 insertions(+), 39 deletions(-)
+ create mode 100644 gcc/testsuite/g++.dg/cpp0x/alias-decl-72.C
+ create mode 100644 gcc/testsuite/g++.dg/cpp0x/alias-decl-72a.C
+
+diff --git a/gcc/cp/pt.c b/gcc/cp/pt.c
+index 5a957141ba3..7ce9ac234f8 100644
+--- a/gcc/cp/pt.c
++++ b/gcc/cp/pt.c
+@@ -13811,45 +13811,6 @@ tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
+ 	  if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
+ 	    return spec;
+ 	}
+-
+-      /* We can see more levels of arguments than parameters if
+-	 there was a specialization of a member template, like
+-	 this:
+-
+-	 template <class T> struct S { template <class U> void f(); }
+-	 template <> template <class U> void S<int>::f(U);
+-
+-	 Here, we'll be substituting into the specialization,
+-	 because that's where we can find the code we actually
+-	 want to generate, but we'll have enough arguments for
+-	 the most general template.
+-
+-	 We also deal with the peculiar case:
+-
+-	 template <class T> struct S {
+-	   template <class U> friend void f();
+-	 };
+-	 template <class U> void f() {}
+-	 template S<int>;
+-	 template void f<double>();
+-
+-	 Here, the ARGS for the instantiation of will be {int,
+-	 double}.  But, we only need as many ARGS as there are
+-	 levels of template parameters in CODE_PATTERN.  We are
+-	 careful not to get fooled into reducing the ARGS in
+-	 situations like:
+-
+-	 template <class T> struct S { template <class U> void f(U); }
+-	 template <class T> template <> void S<T>::f(int) {}
+-
+-	 which we can spot because the pattern will be a
+-	 specialization in this case.  */
+-      int args_depth = TMPL_ARGS_DEPTH (args);
+-      int parms_depth =
+-	TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
+-
+-      if (args_depth > parms_depth && !DECL_TEMPLATE_SPECIALIZATION (t))
+-	args = get_innermost_template_args (args, parms_depth);
+     }
+   else
+     {
+diff --git a/gcc/testsuite/g++.dg/cpp0x/alias-decl-72.C b/gcc/testsuite/g++.dg/cpp0x/alias-decl-72.C
+new file mode 100644
+index 00000000000..8009756dcba
+--- /dev/null
++++ b/gcc/testsuite/g++.dg/cpp0x/alias-decl-72.C
+@@ -0,0 +1,9 @@
++// PR c++/100102
++// { dg-do compile { target c++11 } }
++
++template<int()> struct ratio;
++template<class T, class U> struct duration {
++  static constexpr int _S_gcd();
++  template<class> using __is_harmonic = ratio<_S_gcd>;
++  using type = __is_harmonic<int>;
++};
+diff --git a/gcc/testsuite/g++.dg/cpp0x/alias-decl-72a.C b/gcc/testsuite/g++.dg/cpp0x/alias-decl-72a.C
+new file mode 100644
+index 00000000000..a4443e18f9d
+--- /dev/null
++++ b/gcc/testsuite/g++.dg/cpp0x/alias-decl-72a.C
+@@ -0,0 +1,9 @@
++// PR c++/100102
++// { dg-do compile { target c++11 } }
++
++template<int> struct ratio;
++template<class T> struct duration {
++  static constexpr int _S_gcd();
++  template<class> using __is_harmonic = ratio<(duration::_S_gcd)()>;
++  using type = __is_harmonic<int>;
++};
+-- 
+2.31.1
+
diff --git a/packages/gcc/piclibs.patch b/packages/gcc/piclibs.patch
new file mode 100644
index 0000000000000000000000000000000000000000..0ecb7930675230289be24cdd3b7b2ff9e9b311a2
--- /dev/null
+++ b/packages/gcc/piclibs.patch
@@ -0,0 +1,62 @@
+diff --git a/libgfortran/Makefile.in b/libgfortran/Makefile.in
+index 62b9f7a..7666fdb 100644
+--- a/libgfortran/Makefile.in
++++ b/libgfortran/Makefile.in
+@@ -357,11 +357,11 @@ AUTOMAKE = @AUTOMAKE@
+ AWK = @AWK@
+ CC = @CC@
+ CCDEPMODE = @CCDEPMODE@
+-CFLAGS = @CFLAGS@
++CFLAGS = @CFLAGS@ -fPIC
+ CPP = @CPP@
+-CPPFLAGS = @CPPFLAGS@
++CPPFLAGS = @CPPFLAGS@ -fPIC
+ CYGPATH_W = @CYGPATH_W@
+-DEFS = @DEFS@
++DEFS = @DEFS@ -fPIC
+ DEPDIR = @DEPDIR@
+ DSYMUTIL = @DSYMUTIL@
+ DUMPBIN = @DUMPBIN@
+@@ -371,7 +371,7 @@ ECHO_T = @ECHO_T@
+ EGREP = @EGREP@
+ EXEEXT = @EXEEXT@
+ FC = @FC@
+-FCFLAGS = @FCFLAGS@
++FCFLAGS = @FCFLAGS@ -fPIC
+ FGREP = @FGREP@
+ FPU_HOST_HEADER = @FPU_HOST_HEADER@
+ GREP = @GREP@
+diff --git a/libstdc++-v3/Makefile.in b/libstdc++-v3/Makefile.in
+index bede542..9b3e442 100644
+--- a/libstdc++-v3/Makefile.in
++++ b/libstdc++-v3/Makefile.in
+@@ -115,7 +115,7 @@ CC = @CC@
+ CCODECVT_CC = @CCODECVT_CC@
+ CCOLLATE_CC = @CCOLLATE_CC@
+ CCTYPE_CC = @CCTYPE_CC@
+-CFLAGS = @CFLAGS@
++CFLAGS = @CFLAGS@ -fPIC
+ CLOCALE_CC = @CLOCALE_CC@
+ CLOCALE_H = @CLOCALE_H@
+ CLOCALE_INTERNAL_H = @CLOCALE_INTERNAL_H@
+@@ -124,7 +124,7 @@ CMESSAGES_H = @CMESSAGES_H@
+ CMONEY_CC = @CMONEY_CC@
+ CNUMERIC_CC = @CNUMERIC_CC@
+ CPP = @CPP@
+-CPPFLAGS = @CPPFLAGS@
++CPPFLAGS = @CPPFLAGS@ -fPIC
+ CPU_DEFINES_SRCDIR = @CPU_DEFINES_SRCDIR@
+ CPU_OPT_BITS_RANDOM = @CPU_OPT_BITS_RANDOM@
+ CPU_OPT_EXT_RANDOM = @CPU_OPT_EXT_RANDOM@
+@@ -139,7 +139,7 @@ CYGPATH_W = @CYGPATH_W@
+ C_INCLUDE_DIR = @C_INCLUDE_DIR@
+ DBLATEX = @DBLATEX@
+ DEBUG_FLAGS = @DEBUG_FLAGS@
+-DEFS = @DEFS@
++DEFS = @DEFS@ -fPIC
+ DOT = @DOT@
+ DOXYGEN = @DOXYGEN@
+ DSYMUTIL = @DSYMUTIL@
+-- 
+2.8.3
+
diff --git a/packages/gcc/signal.patch b/packages/gcc/signal.patch
new file mode 100644
index 0000000000000000000000000000000000000000..21bf9e030f44667534d7c9430646924cd467b2b1
--- /dev/null
+++ b/packages/gcc/signal.patch
@@ -0,0 +1,28 @@
+From 6c709b6262e8b6441b1e94526d6d65d4ce7a7dec Mon Sep 17 00:00:00 2001
+From: doko <doko@138bc75d-0d04-0410-961f-82ee72b054a4>
+Date: Thu, 7 Sep 2017 07:18:57 +0000
+Subject: [PATCH] 2017-09-07  Matthias Klose  <doko@ubuntu.com>
+
+        * asan/asan_linux.cc: Include <signal.h>
+
+
+git-svn-id: svn+ssh://gcc.gnu.org/svn/gcc/branches/gcc-5-branch@251830 138bc75d-0d04-0410-961f-82ee72b054a4
+---
+ libsanitizer/asan/asan_linux.cc | 1 +
+ 2 files changed, 5 insertions(+)
+
+diff --git a/libsanitizer/asan/asan_linux.cc b/libsanitizer/asan/asan_linux.cc
+index c504168..59087b9 100644
+--- a/libsanitizer/asan/asan_linux.cc
++++ b/libsanitizer/asan/asan_linux.cc
+@@ -29,6 +29,7 @@
+ #include <dlfcn.h>
+ #include <fcntl.h>
+ #include <pthread.h>
++#include <signal.h>
+ #include <stdio.h>
+ #include <unistd.h>
+ #include <unwind.h>
+-- 
+2.9.3
+
diff --git a/packages/gcc/stack_t-4.9.patch b/packages/gcc/stack_t-4.9.patch
new file mode 100644
index 0000000000000000000000000000000000000000..b894557c8c58d496d5617ef6d928c3e95f04f173
--- /dev/null
+++ b/packages/gcc/stack_t-4.9.patch
@@ -0,0 +1,80 @@
+From 833e00c01e96f61e24cd7ec97b93fad212dc914b Mon Sep 17 00:00:00 2001
+From: doko <doko@138bc75d-0d04-0410-961f-82ee72b054a4>
+Date: Thu, 7 Sep 2017 07:17:17 +0000
+Subject: [PATCH] 2017-09-07  Matthias Klose  <doko@ubuntu.com>
+
+        Backported from mainline
+        2017-07-14  Jakub Jelinek  <jakub@redhat.com>
+
+        PR sanitizer/81066
+        * sanitizer_common/sanitizer_linux.h: Cherry-pick upstream r307969.
+        * sanitizer_common/sanitizer_linux.cc: Likewise.
+        * sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cc: Likewise.
+        * tsan/tsan_platform_linux.cc: Likewise.
+
+
+git-svn-id: svn+ssh://gcc.gnu.org/svn/gcc/branches/gcc-5-branch@251829 138bc75d-0d04-0410-961f-82ee72b054a4
+---
+ libsanitizer/sanitizer_common/sanitizer_linux.cc              |  3 +--
+ libsanitizer/sanitizer_common/sanitizer_linux.h               |  4 +---
+ .../sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cc  |  2 +-
+ libsanitizer/tsan/tsan_platform_linux.cc                      |  2 +-
+ 5 files changed, 15 insertions(+), 7 deletions(-)
+
+diff --git a/libsanitizer/sanitizer_common/sanitizer_linux.cc b/libsanitizer/sanitizer_common/sanitizer_linux.cc
+index 9feb307..821b26d 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_linux.cc
++++ b/libsanitizer/sanitizer_common/sanitizer_linux.cc
+@@ -514,8 +514,7 @@ uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
+ }
+ #endif
+ 
+-uptr internal_sigaltstack(const struct sigaltstack *ss,
+-                         struct sigaltstack *oss) {
++uptr internal_sigaltstack(const void *ss, void *oss) {
+   return internal_syscall(__NR_sigaltstack, (uptr)ss, (uptr)oss);
+ }
+ 
+diff --git a/libsanitizer/sanitizer_common/sanitizer_linux.h b/libsanitizer/sanitizer_common/sanitizer_linux.h
+index 086834c..3a6f4cd 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_linux.h
++++ b/libsanitizer/sanitizer_common/sanitizer_linux.h
+@@ -27,8 +26,7 @@ struct linux_dirent;
+ // Syscall wrappers.
+ uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count);
+ uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5);
+-uptr internal_sigaltstack(const struct sigaltstack* ss,
+-                          struct sigaltstack* oss);
++uptr internal_sigaltstack(const void* ss, void* oss);
+ uptr internal_sigaction(int signum, const __sanitizer_kernel_sigaction_t *act,
+     __sanitizer_kernel_sigaction_t *oldact);
+ uptr internal_sigprocmask(int how, __sanitizer_kernel_sigset_t *set,
+diff --git a/libsanitizer/sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cc b/libsanitizer/sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cc
+index 5881202..c54894d 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cc
++++ b/libsanitizer/sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cc
+@@ -234,7 +234,7 @@ static int TracerThread(void* argument) {
+ 
+   // Alternate stack for signal handling.
+   InternalScopedBuffer<char> handler_stack_memory(kHandlerStackSize);
+-  struct sigaltstack handler_stack;
++  stack_t handler_stack;
+   internal_memset(&handler_stack, 0, sizeof(handler_stack));
+   handler_stack.ss_sp = handler_stack_memory.data();
+   handler_stack.ss_size = kHandlerStackSize;
+diff --git a/libsanitizer/tsan/tsan_platform_linux.cc b/libsanitizer/tsan/tsan_platform_linux.cc
+index 3259131..b8e9078 100644
+--- a/libsanitizer/tsan/tsan_platform_linux.cc
++++ b/libsanitizer/tsan/tsan_platform_linux.cc
+@@ -377,7 +377,7 @@ bool IsGlobalVar(uptr addr) {
+ int ExtractResolvFDs(void *state, int *fds, int nfd) {
+ #if SANITIZER_LINUX
+   int cnt = 0;
+-  __res_state *statp = (__res_state*)state;
++  struct __res_state *statp = (struct __res_state*)state;
+   for (int i = 0; i < MAXNS && cnt < nfd; i++) {
+     if (statp->_u._ext.nsaddrs[i] && statp->_u._ext.nssocks[i] != -1)
+       fds[cnt++] = statp->_u._ext.nssocks[i];
+-- 
+2.9.3
+
diff --git a/packages/gcc/stack_t.patch b/packages/gcc/stack_t.patch
new file mode 100644
index 0000000000000000000000000000000000000000..48a5a47ade1980e4708b8d8cd42992d1d378584f
--- /dev/null
+++ b/packages/gcc/stack_t.patch
@@ -0,0 +1,88 @@
+From 833e00c01e96f61e24cd7ec97b93fad212dc914b Mon Sep 17 00:00:00 2001
+From: doko <doko@138bc75d-0d04-0410-961f-82ee72b054a4>
+Date: Thu, 7 Sep 2017 07:17:17 +0000
+Subject: [PATCH] 2017-09-07  Matthias Klose  <doko@ubuntu.com>
+
+        Backported from mainline
+        2017-07-14  Jakub Jelinek  <jakub@redhat.com>
+
+        PR sanitizer/81066
+        * sanitizer_common/sanitizer_linux.h: Cherry-pick upstream r307969.
+        * sanitizer_common/sanitizer_linux.cc: Likewise.
+        * sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cc: Likewise.
+        * tsan/tsan_platform_linux.cc: Likewise.
+
+
+git-svn-id: svn+ssh://gcc.gnu.org/svn/gcc/branches/gcc-5-branch@251829 138bc75d-0d04-0410-961f-82ee72b054a4
+---
+ libsanitizer/sanitizer_common/sanitizer_linux.cc              |  3 +--
+ libsanitizer/sanitizer_common/sanitizer_linux.h               |  4 +---
+ .../sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cc  |  2 +-
+ libsanitizer/tsan/tsan_platform_linux.cc                      |  2 +-
+ 5 files changed, 15 insertions(+), 7 deletions(-)
+
+diff --git a/libsanitizer/sanitizer_common/sanitizer_linux.cc b/libsanitizer/sanitizer_common/sanitizer_linux.cc
+index 9feb307..821b26d 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_linux.cc
++++ b/libsanitizer/sanitizer_common/sanitizer_linux.cc
+@@ -514,8 +514,7 @@ uptr internal_prctl(int option, uptr arg2, uptr arg3, uptr arg4, uptr arg5) {
+ }
+ #endif
+ 
+-uptr internal_sigaltstack(const struct sigaltstack *ss,
+-                         struct sigaltstack *oss) {
++uptr internal_sigaltstack(const void *ss, void *oss) {
+   return internal_syscall(SYSCALL(sigaltstack), (uptr)ss, (uptr)oss);
+ }
+ 
+diff --git a/libsanitizer/sanitizer_common/sanitizer_linux.h b/libsanitizer/sanitizer_common/sanitizer_linux.h
+index 086834c..3a6f4cd 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_linux.h
++++ b/libsanitizer/sanitizer_common/sanitizer_linux.h
+@@ -18,7 +18,6 @@
+ #include "sanitizer_platform_limits_posix.h"
+ 
+ struct link_map;  // Opaque type returned by dlopen().
+-struct sigaltstack;
+ 
+ namespace __sanitizer {
+ // Dirent structure for getdents(). Note that this structure is different from
+@@ -27,8 +26,7 @@ struct linux_dirent;
+ 
+ // Syscall wrappers.
+ uptr internal_getdents(fd_t fd, struct linux_dirent *dirp, unsigned int count);
+-uptr internal_sigaltstack(const struct sigaltstack* ss,
+-                          struct sigaltstack* oss);
++uptr internal_sigaltstack(const void* ss, void* oss);
+ uptr internal_sigprocmask(int how, __sanitizer_sigset_t *set,
+     __sanitizer_sigset_t *oldset);
+ void internal_sigfillset(__sanitizer_sigset_t *set);
+diff --git a/libsanitizer/sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cc b/libsanitizer/sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cc
+index 5881202..c54894d 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cc
++++ b/libsanitizer/sanitizer_common/sanitizer_stoptheworld_linux_libcdep.cc
+@@ -234,7 +234,7 @@ static int TracerThread(void* argument) {
+ 
+   // Alternate stack for signal handling.
+   InternalScopedBuffer<char> handler_stack_memory(kHandlerStackSize);
+-  struct sigaltstack handler_stack;
++  stack_t handler_stack;
+   internal_memset(&handler_stack, 0, sizeof(handler_stack));
+   handler_stack.ss_sp = handler_stack_memory.data();
+   handler_stack.ss_size = kHandlerStackSize;
+diff --git a/libsanitizer/tsan/tsan_platform_linux.cc b/libsanitizer/tsan/tsan_platform_linux.cc
+index 3259131..b8e9078 100644
+--- a/libsanitizer/tsan/tsan_platform_linux.cc
++++ b/libsanitizer/tsan/tsan_platform_linux.cc
+@@ -377,7 +377,7 @@ bool IsGlobalVar(uptr addr) {
+ int ExtractResolvFDs(void *state, int *fds, int nfd) {
+ #if SANITIZER_LINUX
+   int cnt = 0;
+-  __res_state *statp = (__res_state*)state;
++  struct __res_state *statp = (struct __res_state*)state;
+   for (int i = 0; i < MAXNS && cnt < nfd; i++) {
+     if (statp->_u._ext.nsaddrs[i] && statp->_u._ext.nssocks[i] != -1)
+       fds[cnt++] = statp->_u._ext.nssocks[i];
+-- 
+2.9.3
+
diff --git a/packages/gcc/sys_ustat-4.9.patch b/packages/gcc/sys_ustat-4.9.patch
new file mode 100644
index 0000000000000000000000000000000000000000..75453af3387e5e234bf33476f1b5d0a693a55c35
--- /dev/null
+++ b/packages/gcc/sys_ustat-4.9.patch
@@ -0,0 +1,34 @@
+The sys_ustat.h patch modified for gcc 4.9.x.
+
+diff -Naurb gcc-4.9.4.orig/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc gcc-4.9.4/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+--- gcc-4.9.4.orig/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc	2013-12-19 06:54:11.000000000 -0600
++++ gcc-4.9.4/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc	2018-12-11 15:57:46.901800462 -0600
+@@ -81,7 +81,6 @@
+ #include <sys/statvfs.h>
+ #include <sys/timex.h>
+ #include <sys/user.h>
+-#include <sys/ustat.h>
+ #include <linux/cyclades.h>
+ #include <linux/if_eql.h>
+ #include <linux/if_plip.h>
+@@ -163,7 +162,19 @@
+   unsigned struct_old_utsname_sz = sizeof(struct old_utsname);
+   unsigned struct_oldold_utsname_sz = sizeof(struct oldold_utsname);
+   unsigned struct_itimerspec_sz = sizeof(struct itimerspec);
+-  unsigned struct_ustat_sz = sizeof(struct ustat);
++  // 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) \
++  || defined(__powerpc64__) || defined(__arch64__) || defined(__sparcv9) \
++  || defined(__x86_64__)
++#define SIZEOF_STRUCT_USTAT 32
++#elif defined(__arm__) || defined(__i386__) || defined(__mips__) \
++  || defined(__powerpc__) || defined(__s390__)
++#define SIZEOF_STRUCT_USTAT 20
++#else
++#error Unknown size of struct ustat
++#endif
++  unsigned struct_ustat_sz = SIZEOF_STRUCT_USTAT;
+ #endif // SANITIZER_LINUX
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
diff --git a/packages/gcc/sys_ustat.h.patch b/packages/gcc/sys_ustat.h.patch
new file mode 100644
index 0000000000000000000000000000000000000000..c65757b4eb12c39e03522435b56edc6b220604fd
--- /dev/null
+++ b/packages/gcc/sys_ustat.h.patch
@@ -0,0 +1,63 @@
+From 9569b61168b963a6cea7b782fd350dee489ad42c Mon Sep 17 00:00:00 2001
+From: "H.J. Lu" <hjl.tools@gmail.com>
+Date: Mon, 21 May 2018 13:17:55 -0700
+Subject: [PATCH] libsanitizer: Use pre-computed size of struct ustat for Linux
+
+Cherry-pick compiler-rt revision 333213:
+
+<sys/ustat.h> has been removed from glibc 2.28 by:
+
+commit cf2478d53ad7071e84c724a986b56fe17f4f4ca7
+Author: Adhemerval Zanella <adhemerval.zanella@linaro.org>
+Date:   Sun Mar 18 11:28:59 2018 +0800
+
+    Deprecate ustat syscall interface
+
+This patch uses pre-computed size of struct ustat for Linux.
+
+	PR sanitizer/85835
+	* sanitizer_common/sanitizer_platform_limits_posix.cc: Don't
+	include <sys/ustat.h> for Linux.
+	(SIZEOF_STRUCT_USTAT): New.
+	(struct_ustat_sz): Use SIZEOF_STRUCT_USTAT for Linux.
+---
+ .../sanitizer_platform_limits_posix.cc            | 15 +++++++++++++--
+ 1 file changed, 13 insertions(+), 2 deletions(-)
+
+diff --git a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+index 858bb218450..de18e56d11c 100644
+--- a/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
++++ b/libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cc
+@@ -157,7 +157,6 @@ typedef struct user_fpregs elf_fpregset_t;
+ # include <sys/procfs.h>
+ #endif
+ #include <sys/user.h>
+-#include <sys/ustat.h>
+ #include <linux/cyclades.h>
+ #include <linux/if_eql.h>
+ #include <linux/if_plip.h>
+@@ -250,7 +249,19 @@ namespace __sanitizer {
+ #endif // SANITIZER_LINUX || SANITIZER_FREEBSD
+ 
+ #if SANITIZER_LINUX && !SANITIZER_ANDROID
+-  unsigned struct_ustat_sz = sizeof(struct ustat);
++  // 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) \
++  || defined(__powerpc64__) || defined(__arch64__) || defined(__sparcv9) \
++  || defined(__x86_64__)
++#define SIZEOF_STRUCT_USTAT 32
++#elif defined(__arm__) || defined(__i386__) || defined(__mips__) \
++  || defined(__powerpc__) || defined(__s390__)
++#define SIZEOF_STRUCT_USTAT 20
++#else
++#error Unknown size of struct ustat
++#endif
++  unsigned struct_ustat_sz = SIZEOF_STRUCT_USTAT;
+   unsigned struct_rlimit64_sz = sizeof(struct rlimit64);
+   unsigned struct_statvfs64_sz = sizeof(struct statvfs64);
+ #endif // SANITIZER_LINUX && !SANITIZER_ANDROID
+-- 
+2.17.0
+
+
diff --git a/packages/gcc/ucontext_t-java.patch b/packages/gcc/ucontext_t-java.patch
new file mode 100644
index 0000000000000000000000000000000000000000..a43e0b5aa24d09ca63b47c68038e255803c6bb02
--- /dev/null
+++ b/packages/gcc/ucontext_t-java.patch
@@ -0,0 +1,60 @@
+From 9b9287cde20ea57578cf07efb2a96ed4cc0da36f Mon Sep 17 00:00:00 2001
+From: doko <doko@138bc75d-0d04-0410-961f-82ee72b054a4>
+Date: Thu, 7 Sep 2017 07:22:07 +0000
+Subject: [PATCH] 2017-09-07  Matthias Klose  <doko@ubuntu.com>
+
+        * include/x86_64-signal.h (HANDLE_DIVIDE_OVERFLOW): Replace
+        'struct ucontext' with ucontext_t.
+        * include/i386-signal.h (HANDLE_DIVIDE_OVERFLOW): Likewise.
+        * include/s390-signal.h (HANDLE_DIVIDE_OVERFLOW): Likewise.
+
+
+git-svn-id: svn+ssh://gcc.gnu.org/svn/gcc/branches/gcc-5-branch@251832 138bc75d-0d04-0410-961f-82ee72b054a4
+---
+ libjava/include/i386-signal.h   | 2 +-
+ libjava/include/s390-signal.h   | 2 +-
+ libjava/include/x86_64-signal.h | 2 +-
+ 4 files changed, 10 insertions(+), 3 deletions(-)
+
+diff --git a/libjava/include/i386-signal.h b/libjava/include/i386-signal.h
+index c2409b0..ef77e7e 100644
+--- a/libjava/include/i386-signal.h
++++ b/libjava/include/i386-signal.h
+@@ -29,7 +29,7 @@ static void _Jv_##_name (int, siginfo_t *,			\
+ #define HANDLE_DIVIDE_OVERFLOW						\
+ do									\
+ {									\
+-  struct ucontext *_uc = (struct ucontext *)_p;				\
++  ucontext_t *_uc = (ucontext_t *)_p;					\
+   gregset_t &_gregs = _uc->uc_mcontext.gregs;				\
+   unsigned char *_eip = (unsigned char *)_gregs[REG_EIP];		\
+ 									\
+diff --git a/libjava/include/s390-signal.h b/libjava/include/s390-signal.h
+index 4ca4c10..9261b52 100644
+--- a/libjava/include/s390-signal.h
++++ b/libjava/include/s390-signal.h
+@@ -51,7 +51,7 @@ do									\
+   struct                                                                \
+   {                                                                     \
+     unsigned long int uc_flags;                                         \
+-    struct ucontext *uc_link;                                           \
++    ucontext_t *uc_link;                                                \
+     stack_t uc_stack;                                                   \
+     mcontext_t uc_mcontext;                                             \
+     unsigned long sigmask[2];                                           \
+diff --git a/libjava/include/x86_64-signal.h b/libjava/include/x86_64-signal.h
+index 12383b5..e36c5a3 100644
+--- a/libjava/include/x86_64-signal.h
++++ b/libjava/include/x86_64-signal.h
+@@ -28,7 +28,7 @@ static void _Jv_##_name (int, siginfo_t *,			\
+ #define HANDLE_DIVIDE_OVERFLOW						\
+ do									\
+ {									\
+-  struct ucontext *_uc = (struct ucontext *)_p;				\
++  ucontext_t *_uc = (ucontext_t *)_p;					\
+   gregset_t &_gregs = _uc->uc_mcontext.gregs;				\
+   unsigned char *_rip = (unsigned char *)_gregs[REG_RIP];		\
+ 									\
+-- 
+2.9.3
+
diff --git a/packages/gcc/ucontext_t.patch b/packages/gcc/ucontext_t.patch
new file mode 100644
index 0000000000000000000000000000000000000000..a4f04b4715286bbe86ea141ccd257260d8320dd9
--- /dev/null
+++ b/packages/gcc/ucontext_t.patch
@@ -0,0 +1,189 @@
+From ecf0d1a107133c715763940c2b197aa814710e1b Mon Sep 17 00:00:00 2001
+From: jsm28 <jsm28@138bc75d-0d04-0410-961f-82ee72b054a4>
+Date: Tue, 4 Jul 2017 10:25:10 +0000
+Subject: [PATCH] Use ucontext_t not struct ucontext in linux-unwind.h files.
+
+Current glibc no longer gives the ucontext_t type the tag struct
+ucontext, to conform with POSIX namespace rules.  This requires
+various linux-unwind.h files in libgcc, that were previously using
+struct ucontext, to be fixed to use ucontext_t instead.  This is
+similar to the removal of the struct siginfo tag from siginfo_t some
+years ago.
+
+This patch changes those files to use ucontext_t instead.  As the
+standard name that should be unconditionally safe, so this is not
+restricted to architectures supported by glibc, or conditioned on the
+glibc version.
+
+Tested compilation together with current glibc with glibc's
+build-many-glibcs.py.
+
+	* config/aarch64/linux-unwind.h (aarch64_fallback_frame_state),
+	config/alpha/linux-unwind.h (alpha_fallback_frame_state),
+	config/bfin/linux-unwind.h (bfin_fallback_frame_state),
+	config/i386/linux-unwind.h (x86_64_fallback_frame_state,
+	x86_fallback_frame_state), config/m68k/linux-unwind.h (struct
+	uw_ucontext), config/nios2/linux-unwind.h (struct nios2_ucontext),
+	config/pa/linux-unwind.h (pa32_fallback_frame_state),
+	config/sh/linux-unwind.h (sh_fallback_frame_state),
+	config/tilepro/linux-unwind.h (tile_fallback_frame_state),
+	config/xtensa/linux-unwind.h (xtensa_fallback_frame_state): Use
+	ucontext_t instead of struct ucontext.
+
+
+git-svn-id: svn+ssh://gcc.gnu.org/svn/gcc/branches/gcc-5-branch@249958 138bc75d-0d04-0410-961f-82ee72b054a4
+---
+ libgcc/config/aarch64/linux-unwind.h |  2 +-
+ libgcc/config/alpha/linux-unwind.h   |  2 +-
+ libgcc/config/bfin/linux-unwind.h    |  2 +-
+ libgcc/config/i386/linux-unwind.h    |  4 ++--
+ libgcc/config/m68k/linux-unwind.h    |  2 +-
+ libgcc/config/nios2/linux-unwind.h   |  2 +-
+ libgcc/config/pa/linux-unwind.h      |  2 +-
+ libgcc/config/sh/linux-unwind.h      |  2 +-
+ libgcc/config/tilepro/linux-unwind.h |  2 +-
+ libgcc/config/xtensa/linux-unwind.h  |  2 +-
+ 11 files changed, 25 insertions(+), 11 deletions(-)
+
+diff --git a/libgcc/config/aarch64/linux-unwind.h b/libgcc/config/aarch64/linux-unwind.h
+index 86d17b1..909f68f 100644
+--- a/libgcc/config/aarch64/linux-unwind.h
++++ b/libgcc/config/aarch64/linux-unwind.h
+@@ -52,7 +52,7 @@ aarch64_fallback_frame_state (struct _Unwind_Context *context,
+   struct rt_sigframe
+   {
+     siginfo_t info;
+-    struct ucontext uc;
++    ucontext_t uc;
+   };
+ 
+   struct rt_sigframe *rt_;
+diff --git a/libgcc/config/alpha/linux-unwind.h b/libgcc/config/alpha/linux-unwind.h
+index d65474f..9a226b1 100644
+--- a/libgcc/config/alpha/linux-unwind.h
++++ b/libgcc/config/alpha/linux-unwind.h
+@@ -51,7 +51,7 @@ alpha_fallback_frame_state (struct _Unwind_Context *context,
+     {
+       struct rt_sigframe {
+ 	siginfo_t info;
+-	struct ucontext uc;
++	ucontext_t uc;
+       } *rt_ = context->cfa;
+       sc = &rt_->uc.uc_mcontext;
+     }
+diff --git a/libgcc/config/bfin/linux-unwind.h b/libgcc/config/bfin/linux-unwind.h
+index 0c270e4..7fa95d2 100644
+--- a/libgcc/config/bfin/linux-unwind.h
++++ b/libgcc/config/bfin/linux-unwind.h
+@@ -52,7 +52,7 @@ bfin_fallback_frame_state (struct _Unwind_Context *context,
+ 	void *puc;
+ 	char retcode[8];
+ 	siginfo_t info;
+-	struct ucontext uc;
++	ucontext_t uc;
+       } *rt_ = context->cfa;
+ 
+       /* The void * cast is necessary to avoid an aliasing warning.
+diff --git a/libgcc/config/i386/linux-unwind.h b/libgcc/config/i386/linux-unwind.h
+index e54bf73..d35fc45 100644
+--- a/libgcc/config/i386/linux-unwind.h
++++ b/libgcc/config/i386/linux-unwind.h
+@@ -58,7 +58,7 @@ x86_64_fallback_frame_state (struct _Unwind_Context *context,
+   if (*(unsigned char *)(pc+0) == 0x48
+       && *(unsigned long long *)(pc+1) == RT_SIGRETURN_SYSCALL)
+     {
+-      struct ucontext *uc_ = context->cfa;
++      ucontext_t *uc_ = context->cfa;
+       /* The void * cast is necessary to avoid an aliasing warning.
+          The aliasing warning is correct, but should not be a problem
+          because it does not alias anything.  */
+@@ -138,7 +138,7 @@ x86_fallback_frame_state (struct _Unwind_Context *context,
+ 	siginfo_t *pinfo;
+ 	void *puc;
+ 	siginfo_t info;
+-	struct ucontext uc;
++	ucontext_t uc;
+       } *rt_ = context->cfa;
+       /* The void * cast is necessary to avoid an aliasing warning.
+          The aliasing warning is correct, but should not be a problem
+diff --git a/libgcc/config/m68k/linux-unwind.h b/libgcc/config/m68k/linux-unwind.h
+index fb79a4d..b2f5ea4 100644
+--- a/libgcc/config/m68k/linux-unwind.h
++++ b/libgcc/config/m68k/linux-unwind.h
+@@ -33,7 +33,7 @@ see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
+ /* <sys/ucontext.h> is unfortunately broken right now.  */
+ struct uw_ucontext {
+ 	unsigned long	  uc_flags;
+-	struct ucontext  *uc_link;
++	ucontext_t	 *uc_link;
+ 	stack_t		  uc_stack;
+ 	mcontext_t	  uc_mcontext;
+ 	unsigned long	  uc_filler[80];
+diff --git a/libgcc/config/nios2/linux-unwind.h b/libgcc/config/nios2/linux-unwind.h
+index dff1c20..1d88afe 100644
+--- a/libgcc/config/nios2/linux-unwind.h
++++ b/libgcc/config/nios2/linux-unwind.h
+@@ -38,7 +38,7 @@ struct nios2_mcontext {
+ 
+ struct nios2_ucontext {
+   unsigned long uc_flags;
+-  struct ucontext *uc_link;
++  ucontext_t *uc_link;
+   stack_t uc_stack;
+   struct nios2_mcontext uc_mcontext;
+   sigset_t uc_sigmask;	/* mask last for extensibility */
+diff --git a/libgcc/config/pa/linux-unwind.h b/libgcc/config/pa/linux-unwind.h
+index 0149468..9157535 100644
+--- a/libgcc/config/pa/linux-unwind.h
++++ b/libgcc/config/pa/linux-unwind.h
+@@ -80,7 +80,7 @@ pa32_fallback_frame_state (struct _Unwind_Context *context,
+   struct sigcontext *sc;
+   struct rt_sigframe {
+     siginfo_t info;
+-    struct ucontext uc;
++    ucontext_t uc;
+   } *frame;
+ 
+   /* rt_sigreturn trampoline:
+diff --git a/libgcc/config/sh/linux-unwind.h b/libgcc/config/sh/linux-unwind.h
+index e63091f..67033f0 100644
+--- a/libgcc/config/sh/linux-unwind.h
++++ b/libgcc/config/sh/linux-unwind.h
+@@ -180,7 +180,7 @@ sh_fallback_frame_state (struct _Unwind_Context *context,
+     {
+       struct rt_sigframe {
+ 	siginfo_t info;
+-	struct ucontext uc;
++	ucontext_t uc;
+       } *rt_ = context->cfa;
+       /* The void * cast is necessary to avoid an aliasing warning.
+          The aliasing warning is correct, but should not be a problem
+diff --git a/libgcc/config/tilepro/linux-unwind.h b/libgcc/config/tilepro/linux-unwind.h
+index fd83ba7..e3c9ef0 100644
+--- a/libgcc/config/tilepro/linux-unwind.h
++++ b/libgcc/config/tilepro/linux-unwind.h
+@@ -61,7 +61,7 @@ tile_fallback_frame_state (struct _Unwind_Context *context,
+   struct rt_sigframe {
+     unsigned char save_area[C_ABI_SAVE_AREA_SIZE];
+     siginfo_t info;
+-    struct ucontext uc;
++    ucontext_t uc;
+   } *rt_;
+ 
+   /* Return if this is not a signal handler.  */
+diff --git a/libgcc/config/xtensa/linux-unwind.h b/libgcc/config/xtensa/linux-unwind.h
+index 9a67b5d..98b7ea6 100644
+--- a/libgcc/config/xtensa/linux-unwind.h
++++ b/libgcc/config/xtensa/linux-unwind.h
+@@ -67,7 +67,7 @@ xtensa_fallback_frame_state (struct _Unwind_Context *context,
+ 
+   struct rt_sigframe {
+     siginfo_t info;
+-    struct ucontext uc;
++    ucontext_t uc;
+   } *rt_;
+ 
+   /* movi a2, __NR_rt_sigreturn; syscall */
+-- 
+2.9.3
+
diff --git a/packages/gcc/zstd.patch b/packages/gcc/zstd.patch
new file mode 100644
index 0000000000000000000000000000000000000000..8fb7583a0c221d5beff8ad8fbcbf97468814848a
--- /dev/null
+++ b/packages/gcc/zstd.patch
@@ -0,0 +1,43 @@
+--- a/gcc/Makefile.in
++++ b/gcc/Makefile.in
+@@ -1075,7 +1075,8 @@ GNATMAKE = @GNATMAKE@
+ # Libs needed (at present) just for jcf-dump.
+ LDEXP_LIB = @LDEXP_LIB@
+ 
+-ZSTD_LIB = @ZSTD_LIB@
++ZSTD_INC = @ZSTD_CPPFLAGS@
++ZSTD_LIB = @ZSTD_LDFLAGS@ @ZSTD_LIB@
+ 
+ # Likewise, for use in the tools that must run on this machine
+ # even if we are cross-building GCC.
+@@ -2275,7 +2276,7 @@ CFLAGS-version.o += -DBASEVER=$(BASEVER_s) -DDATESTAMP=$(DATESTAMP_s) \
+ version.o: $(REVISION) $(DATESTAMP) $(BASEVER) $(DEVPHASE)
+ 
+ # lto-compress.o needs $(ZLIBINC) added to the include flags.
+-CFLAGS-lto-compress.o += $(ZLIBINC)
++CFLAGS-lto-compress.o += $(ZLIBINC) $(ZSTD_INC)
+ 
+ CFLAGS-lto-streamer-in.o += -DTARGET_MACHINE=\"$(target_noncanonical)\"
+ 
+--- a/gcc/configure
++++ b/gcc/configure
+@@ -786,6 +786,8 @@ LTLIBICONV
+ LIBICONV
+ ZSTD_LIB
+ ZSTD_INCLUDE
++ZSTD_LDFLAGS
++ZSTD_CPPFLAGS
+ DL_LIB
+ LDEXP_LIB
+ EXTRA_GCC_LIBS
+--- a/gcc/configure.ac
++++ b/gcc/configure.ac
+@@ -1339,6 +1339,8 @@ AC_SUBST(ZSTD_INCLUDE)
+ AC_SUBST(ZSTD_LIB)
+ ZSTD_CPPFLAGS=
+ ZSTD_LDFLAGS=
++AC_SUBST(ZSTD_CPPFLAGS)
++AC_SUBST(ZSTD_LDFLAGS)
+ AC_ARG_WITH(zstd,
+ 	[AS_HELP_STRING([--with-zstd=PATH],
+ 		[specify prefix directory for installed zstd library.