# HG changeset patch
# User Jeroen Demeyer <jdemeyer@cage.ugent.be>
# Date 1334060092 -7200
# Node ID 7353f501cc393146517fbc253a2972e45dba4883
# Parent  f0de181e1710e4fb5e9227cefed4b9d6656a3ae4
Trac #11616: upgrade MPIR to version 2.4.0; many other fixes
 * Before enabling `-march=native`, minimalistically check whether the
   system's assembler also understands the instructions the compiler emits
   with that option.  (Work-around for e.g. GCC 4.6.3 on MacOS X 10.x and
   Intel Core i7-family CPUs with AVX.)
 * Do not unconditionally unset `PYTHON`, since Sage (>=5.0.beta10) no longer
   pollutes the environment with its package version variables, which previous-
   ly confused yasm's `configure`.
 * Fix extraction of `__GMP_CC` and `__GMP_CFLAGS` from `gmp.h`, since MPIR
   meanwhile defines these to preprocessor variables (rather than literals).
   Also don't use `\+` in `sed` patterns, as this is less portable.
 * Work around GCC 4.7.0 bug (compilation error) on Linux ia64 (Itanium) by
   almost completely disabling optimization on that platform if GCC 4.7.x
   is detected.  This doesn't hurt much if we later rebuild MPIR with a (non-
   broken) GCC from the new GCC spkg.  Cf. #12765.
 * Do not build the C++ interface and static libraries when bootstrapping the
   GCC spkg, i.e. if `SAGE_BUILD_TOOLCHAIN=yes`.  (GMP/MPIR is a prerequisite
   for it, and MPIR will later get rebuilt with both enabled, with the newly
   built GCC.)  Cf. #12782.
 * Fix a potential race condition in yasm's build by patching the re2c source.
   Cf. #11844.
 * Add "`patch` loop" to apply any patches (`*.patch`) located in `patches/`.
   Currently only the re2c patch matches that; the prepatched header to support
   Sun's C compiler is still copied over (and only on SunOS, although it doesn't
   do any harm on other platforms).
 * Minor clean-up; e.g. redirect error messages and warnings to `stderr`,
   quote parameter to `--libdir`, add some comments and messages, also save
   user's setting of `LDFLAGS` and `ABI`.

diff --git a/SPKG.txt b/SPKG.txt
--- a/SPKG.txt
+++ b/SPKG.txt
@@ -20,26 +20,71 @@
 
 == Dependencies ==
  * iconv
+ * GNU patch
 
 == Special Update/Build Instructions ==
- * TODO: Use 'patch' rather than copying over patched upstream files.
-         (The currently patched file for Sun CC on SunOS has to be refreshed on
-         each upgrade.)
- * Make sure the patches still apply; also, putting "-Wl,z,noexecstack"
+ * TODO:
+   - Use 'patch' also to (unconditionally) apply the harmless patch for Sun CC 
+     (on SunOS), as the current prepatched file which is still copied over has
+     to get refreshed on each upgrade.
+   - Perhaps also modify CXXFLAGS (and/or CPPFLAGS).
+   - We currently don't use anything of GMP's/MPIR's CC setting, and matching
+     with the current compiler (`$CC`) is perhaps suboptimal.
+ * Make sure the patches still apply; also, putting "-Wl,-z,noexecstack"
    into LDFLAGS might not be necessary for later versions.
  * Perhaps make sure we still delete the correct files on 32-bit MacOS X
    on Intel hardware (x86) to not break PIC there.
+ * The work-around for the broken GCC 4.7.0 on Linux ia64 (Itanium) is current-
+   ly applied for any 4.7.x version (of course only on that platform), as it
+   seems unlikely that the bug which breaks the build of MPIR gets fixed soon.
+   In case GCC 4.7.1 or a later version is meanwhile released, one should check
+   whether the build is still broken with this or these, and eventually change
+   the version pattern accordingly.
  * Remove some files / directories not needed for Sage from upstream:
      rm -rf src/build.vc*             # Microsoft Visual C build files
      rm -rf src/yasm/Mkfiles/{dj,vc*} # DJGPP, Microsoft Visual C
    (Saves 13 of 40 MB uncompressed.)
 
 === Patches ===
- * We currently only apply a trivial patch to gmp-h.in on SunOS such that
-   MPIR would compile with Sun CC there. See also `spkg-install`.
+ * We currently apply a trivial patch to gmp-h.in on SunOS such that
+   MPIR would compile with Sun CC there.  See also `spkg-install`.
+   This patch could be applied on all platforms, as the changes only take
+   effect if the preprocessor variable `__SUNPRO_CC` is defined.
+ * We apply a simple patch to upstream yasm's re2c code, to avoid a potential
+   race condition when building yasm in parallel.  (Cf. #11844.)
 
 == Changelog ==
 
+=== mpir-2.4.0.p2 (Leif Leonhardy, April 4th, 2012) ===
+ #11616 (upgrading MPIR), further fixes:
+ * Before enabling `-march=native`, minimalistically check whether the
+   system's assembler also understands the instructions the compiler emits
+   with that option.  (Work-around for e.g. GCC 4.6.3 on MacOS X 10.x and
+   Intel Core i7-family CPUs with AVX.)
+ * Do not unconditionally unset `PYTHON`, since Sage (>=5.0.beta10) no longer
+   pollutes the environment with its package version variables, which previous-
+   ly confused yasm's `configure`.
+ * Fix extraction of `__GMP_CC` and `__GMP_CFLAGS` from `gmp.h`, since MPIR
+   meanwhile defines these to preprocessor variables (rather than literals).
+   Also don't use `\+` in `sed` patterns, as this is less portable.
+ * Work around GCC 4.7.0 bug (compilation error) on Linux ia64 (Itanium) by
+   almost completely disabling optimization on that platform if GCC 4.7.x
+   is detected.  This doesn't hurt much if we later rebuild MPIR with a (non-
+   broken) GCC from the new GCC spkg.  Cf. #12765.
+ * Do not build the C++ interface and static libraries when bootstrapping the
+   GCC spkg, i.e. if `SAGE_BUILD_TOOLCHAIN=yes`.  (GMP/MPIR is a prerequisite
+   for it, and MPIR will later get rebuilt with both enabled, with the newly
+   built GCC.)  Cf. #12782.
+ * Fix a potential race condition in yasm's build by patching the re2c source.
+   Cf. #11844.
+ * Add "`patch` loop" to apply any patches (`*.patch`) located in `patches/`.
+   Currently only the re2c patch matches that; the prepatched header to support
+   Sun's C compiler is still copied over (and only on SunOS, although it doesn't
+   do any harm on other platforms).
+ * Minor clean-up; e.g. redirect error messages and warnings to `stderr`,
+   quote parameter to `--libdir`, add some comments and messages, also save
+   user's setting of `LDFLAGS` and `ABI`.
+
 === mpir-2.4.0.p1 (Leif Leonhardy, March 21st, 2012) ===
  * Upstream upgrade to MPIR 2.4.0 (#11616).
    The 2.4.0.p0 spkg isn't in this history, as it was based
diff --git a/patches/yasm__tools__re2c__code.c.patch b/patches/yasm__tools__re2c__code.c.patch
new file mode 100644
--- /dev/null
+++ b/patches/yasm__tools__re2c__code.c.patch
@@ -0,0 +1,38 @@
+--- src/yasm/tools/re2c/code.c	2011-03-05 14:47:11.000000000 +0100
++++ src/yasm/tools/re2c/code.c	2012-04-05 12:34:44.958541522 +0200
+@@ -1,5 +1,6 @@
+ #include <stdlib.h>
+ #include <string.h>
++#include <errno.h>
+ #include <ctype.h>
+ #include "tools/re2c/substr.h"
+ #include "tools/re2c/globals.h"
+@@ -10,7 +11,7 @@
+     while (value >= vUsedLabelAlloc) {
+ 	vUsedLabels = realloc(vUsedLabels, vUsedLabelAlloc * 2);
+ 	if (!vUsedLabels) {
+-	    fputs("Out of memory.\n", stderr);
++	    fputs("Error: re2c: Out of memory.\n", stderr);
+ 	    exit(EXIT_FAILURE);
+ 	}
+ 	memset(vUsedLabels + vUsedLabelAlloc, 0, vUsedLabelAlloc);
+@@ -844,14 +845,17 @@
+     nOrgOline = oline;
+     maxFillIndexes = vFillIndexes;
+     orgVFillIndexes = vFillIndexes;
+-    tmpo = fopen("re2c.tmp", "wt");
++    if (!(tmpo = tmpfile()))
++    {
++        fprintf(stderr, "Error: re2c: tmpfile(): %s\n", strerror(errno));
++        exit(EXIT_FAILURE);
++    }
+     for(s = d->head; s; s = s->next){
+ 	int readCh = 0;
+ 	State_emit(s, tmpo, &readCh);
+ 	Go_genGoto(&s->go, tmpo, s, s->next, &readCh);
+     }
+     fclose(tmpo);
+-    remove("re2c.tmp");
+     maxFillIndexes = vFillIndexes;
+     vFillIndexes = orgVFillIndexes;
+     oline = nOrgOline;
diff --git a/spkg-check b/spkg-check
--- a/spkg-check
+++ b/spkg-check
@@ -1,8 +1,8 @@
 #!/usr/bin/env bash
 
 if [ -z "$SAGE_LOCAL" ]; then
-    echo "Error: SAGE_LOCAL undefined - exiting..."
-    echo "Maybe run 'sage -sh'?"
+    echo >&2 "Error: SAGE_LOCAL undefined - exiting..."
+    echo >&2 "Maybe run 'sage -sh'?"
     exit 1
 fi
 
@@ -11,9 +11,10 @@
 # We don't have to set up any environment variables here since the
 # Makefiles already have them from 'configure'.
 
+echo "Now building and running MPIR's test suite..."
 $MAKE check
 if [ $? -ne 0 ]; then
-    echo "Error: The MPIR test suite failed."
+    echo >&2 "Error: The MPIR test suite failed."
     exit 1
 fi
 
diff --git a/spkg-install b/spkg-install
--- a/spkg-install
+++ b/spkg-install
@@ -6,13 +6,15 @@
 ###############################################################################
 
 if [ -z "$SAGE_LOCAL" ]; then
-    echo "Error: SAGE_LOCAL undefined - exiting..."
-    echo "Maybe run 'sage -sh'?"
+    echo >&2 "Error: SAGE_LOCAL undefined - exiting..."
+    echo >&2 "Maybe run 'sage -sh'?"
     exit 1
 fi
 
 CUR=`pwd`
 
+cd src/
+
 ###############################################################################
 # Apply patches (if any):
 ###############################################################################
@@ -25,13 +27,22 @@
     #       has to be refreshed on each new release, since gmp-h.in also
     #       contains the full version number.
     echo "Copying a version of gmp-h.in which is patched for Sun Studio..."
-    cp patches/gmp-h.in src/
+    cp ../patches/gmp-h.in . # We are in src/.
     if [ $? -ne 0 ]; then
-        echo "Error: Failed to patch MPIR for Sun Studio."
+        echo >&2 "Error: Failed to patch MPIR for Sun Studio."
         exit 1
     fi
 fi
 
+echo "Applying further patches (if any) to upstream sources..."
+for patch in ../patches/*.patch; do
+    patch -p1 <"$patch"
+    if [ $? -ne 0 ]; then
+        echo >&2 "Error: '$patch' failed to apply."
+        exit 1
+    fi
+done
+
 ###############################################################################
 # Previous MPIR installations are only removed after a *successful* (re)build,
 # before installing the new one. (Done below.)
@@ -71,24 +82,38 @@
 {
     # Internal sanity check:
     if [ $# -ne 1 ]; then
-        echo "Error: get_upstream_selected_cflags() requires 'file' parameter."
+        echo >&2 "Error: get_upstream_selected_cflags() requires 'file' parameter."
         exit 1
     fi
     header_file=$1
-    # We'll probably have to change the following patterns (conditionally) when we
-    # upgrade to MPIR >=2.5.0(?), since MPIR's gmp.h was changed to define __GMP_CC
-    # to (literally) __MPIR_CC, and likewise __GMP_CFLAGS to __MPIR_CFLAGS.
-    # I.e., in later releases __MPIR_CC and __MPIR_CFLAGS will contain the real strings
-    # we need (unless they again change this; I've already complained about that).
-    gmp_cc_pat='/^[ 	]*#[ 	]*define[ 	]\+__GMP_CC[ 	]\+/s/.*"\([^"]*\)"/\1/p'
-    gmp_cflags_pat='/^[ 	]*#[ 	]*define[ 	]\+__GMP_CFLAGS[ 	]\+/s/.*"\([^"]*\)"/\1/p'
     if ! [ -f "$header_file" ]; then
         upstream_cc=""
         upstream_cflags=""
         return 1
     fi
+    # The following patterns only extract the contents of (double-quoted) strings:
+    gmp_cc_pat='/^[ 	]*#[ 	]*define[ 	]\{1,\}__GMP_CC[ 	]\{1,\}/s/.*"\([^"]*\)"/\1/p'
+    gmp_cflags_pat='/^[ 	]*#[ 	]*define[ 	]\{1,\}__GMP_CFLAGS[ 	]\{1,\}/s/.*"\([^"]*\)"/\1/p'
+    # Extract preprocessor definitions of __GMP_CC and __GMP_CFLAGS:
     upstream_cc=`sed -n -e "$gmp_cc_pat" "$header_file"`
     upstream_cflags=`sed -n -e "$gmp_cflags_pat" "$header_file"`
+    # At least /some/ newer versions of MPIR define __GMP_CC and __GMP_CFLAGS
+    # (also in gmp.h! -- how compatible is that?) to (literally) __MPIR_CC and
+    # __MPIR_CFLAGS, respectively, i.e., to preprocessor variables, so we might
+    # have to get the real strings from their definitions:
+    # (Since we currently only match string literals above, both variables would
+    # be empty in that case, and not contain the names of preprocessor variables.
+    # We could change the patterns to actually match any definition / "value".) 
+    case "$upstream_cc" in __MPIR_CC|"")
+        upstream_cc=`sed -n -e "${gmp_cc_pat/GMP/MPIR}" "$header_file"`
+    esac
+    case "$upstream_cflags" in __MPIR_CFLAGS|"")
+        upstream_cflags=`sed -n -e "${gmp_cflags_pat/GMP/MPIR}" "$header_file"`
+    esac
+    # Upstream-selected CFLAGS may be empty, CC shouldn't:
+    if [ -z "$upstream_cc" ]; then
+        return 1
+    fi
     return 0
 }
 
@@ -96,7 +121,7 @@
 {
     # Internal sanity check:
     if [ $# -lt 1 ]; then
-        echo "Error: get_processor_specific_cflags() requires 'CFLAGS' parameter."
+        echo >&2 "Error: get_processor_specific_cflags() requires 'CFLAGS' parameter."
         exit 1
     fi
     flags=$@
@@ -109,6 +134,9 @@
             # We could add further '-m' or '-f' options here, but note that
             # this function is also used to determine if the user specified
             # some, which we don't want to override.
+            # AFAIK, MPIR currently uses / defines at most '-m{arch,cpu,tune}',
+            # not more specific / additional ones like e.g. '-mavx' or '-mvsx'.
+            # (-leif, 04/2012)
         esac
     done
     echo $arch_flags
@@ -121,29 +149,56 @@
     # (Compilers other than 'gcc' might support it as well, in which case the
     # following also works. Other flavours could be added, too.)
     if touch foo.c && $CC -march=native -c foo.c &>/dev/null; then
-        echo "-march=native"
+        # Ok, the compiler (presumably GCC) understands '-march=native', which
+        # doesn't yet mean the *assembler* will know the fancy instructions
+        # the compiler emits with that option.
+        # For example, Apple's assembler on Mac OS X 10.7.1 apparently doesn't
+        # yet support AVX, which could also cause MPIR's 'configure' to fail.
+        cat >foo.c <<-"EOF"
+		double d;
+		unsigned long fancy_insns() { return (unsigned long) d; }
+		int main () { return 0; }
+	EOF
+        if $CC -march=native -o foo foo.c &>/dev/null && ./foo >/dev/null; then
+            echo "-march=native"
+        else
+            echo >&2 "Warning: Your assembler apparently doesn't understand the instructions"
+            echo >&2 "         your compiler ($CC) generates with '-march=native'."
+            echo >&2 "         You might also try to compile MPIR with (e.g.)"
+            echo >&2 "             CFLAGS=\"-march=native -mno-avx\""
+            echo >&2 "         to disable specific instruction set extension (in this case, AVX)."
+        fi
     fi
-    rm -f foo.* >/dev/null
+    rm -f foo foo.* >/dev/null
 }
 
 ###############################################################################
 # Set up environment variables:
 ###############################################################################
 
-# The Yasm build uses PYTHON from the environment to find python, so unset
-# it since the setting from 'spkg/standard/newest_version' confuses it:
-unset PYTHON
-# This can be removed once #10492 has been merged, which turns the "package
-# version" environment variables into solely `make` variables, such that the
-# (shell) environment does no longer get polluted. 
+# The Yasm build uses PYTHON from the environment to find the Python interpreter,
+# so unset it in case it apparently contains nothing useful (like it did in Sage
+# versions prior to 5.0.beta10; cf. #10492), to not break Yasm's 'configure':
+if ! $PYTHON --version &>/dev/null; then
+    # Only issue a warning if it was really non-empty, to not confuse users:
+    if [ -n "$PYTHON" ]; then
+        echo >&2 "Warning: Unsetting PYTHON (=\"$PYTHON\"), since it doesn't seem"
+        echo >&2 "         to contain the name of / path to a Python interpreter."
+    fi
+    unset PYTHON
+fi
 
 user_cflags=$CFLAGS # Save them. 'sage-env' sets CC, but not CFLAGS.
-required_cflags="" # Additional mandatory settings required by Sage, accumulated below.
-default_cflags="" # Spkg defaults that can and might get overridden.
+required_cflags=""  # Additional mandatory settings required by Sage, accumulated below.
+default_cflags=""   # Spkg defaults that can and might get overridden.
+user_ldflags=$LDFLAGS # Save them.
+required_ldflags=""   # Additional mandatory settings required by Sage, accumulated below.
+user_abi=$ABI # Just save it.
+# In case we changed CPPFLAGS or CXXFLAGS, too, we should save the user's here as well.
+# We don't have to add (e.g.) '-m64' to CFLAGS/CPPFLAGS/CXXFLAGS/LDFLAGS, since
+# MPIR's 'configure' is smart enough to add it if necessary or appropriate.
 
-# Newer autotools may put libs into .../lib64 (on 64-bit systems):
-SAGE_CONF_OPTS=--libdir="$SAGE_LOCAL/lib"
-# (Further options to `configure` are added below.)
+SAGE_CONF_OPTS="" # Clear them. (Further options to `configure` are added below.)
 
 
 if [ -z "$CFLAG32" ]; then
@@ -157,7 +212,7 @@
 if [ "$SAGE_DEBUG" = yes ]; then
     # Disable optimization, add debug symbols:
     required_cflags="$required_cflags -g -O0"
-    echo "Warning: Building MPIR with SAGE_DEBUG=yes disables optimization."
+    echo >&2 "Warning: Building MPIR with SAGE_DEBUG=yes disables optimization."
 else
     # Add debug symbols by default, enable optimization, but do not (yet)
     # add processor-specific flags (these are eventually added later):
@@ -167,7 +222,7 @@
 
 case "$UNAME" in
     SunOS)
-        if [ "$SAGE64" = "yes" ]; then
+        if [ "$SAGE64" = yes ]; then
             echo "Building a 64-bit version of MPIR." 
             ABI=64
         else
@@ -175,17 +230,18 @@
             ABI=32
         fi;;
     Darwin)
-        if [ "$SAGE64" = "yes" ]; then
-            # Note that we do not support 64-bit builds on PPC at all,
+        if [ "$SAGE64" = yes ]; then
+            # Note that we do not support 64-bit builds on MacOS X PPC at all,
             # so we don't special-case on the architecture here.
             echo "Building a 64-bit version of MPIR."
             ABI=64
         else
-            # Do not set ABI=32 on OS X 10.6 (Darwin 10) and later, since
+            # Do not set ABI=32 on MacOS X 10.6 (Darwin 10) and later, since
             # there everything defaults to 64-bit:
             if [ "`uname -r | sed 's/\..*//'`" -lt 10 ]; then
                 # Assume MacOS X 10.4 or 10.5 (Darwin 8 or 9); also, PPC CPUs
                 # are only supported by these, not later versions.
+                echo "Building a 32-bit version of MPIR, which is the only supported option."
                 ABI=32
                 case "`uname -m`" in
                     i[3456]86)
@@ -198,14 +254,18 @@
                         required_cflags="$required_cflags -Wa,-force_cpusubtype_ALL"
                         ;;
                 esac
+            else
+                # Darwin 10 (MacOS X 10.6) or later, SAGE64 not "yes"
+                # We don't have to set ABI here.
+                echo "Building a 64-bit version of MPIR, which is the default."
             fi
-        fi;;
+        fi
+        ;; # Darwin
     Linux)
         # Work around (erroneously) set "executable stack" attributes,
         # causing runtime errors on Fedora 14 and other SELinux-enabled
         # systems:
-        LDFLAGS="$LDFLAGS -Wl,-z,noexecstack"
-        export LDFLAGS # perhaps redundant, but safe(r)
+        required_ldflags="$required_ldflags -Wl,-z,noexecstack"
 
         if [ "$SAGE_FAT_BINARY" = "yes" ]; then
             # For now we do the same thing -- namely "--enable-fat" --
@@ -220,7 +280,7 @@
                 SAGE_CONF_OPTS="$SAGE_CONF_OPTS --enable-fat"
                 ;;
             *) # e.g. ia64 (Itanium) or PPC (ppc, ppc64)
-                echo "Warning: A \"fat binary\" build is currently not" \
+                echo >&2 "Warning: A \"fat binary\" build is currently not" \
                     "supported on this CPU architecture."
                 # XXX exit 1 ?
             esac
@@ -256,28 +316,53 @@
                 echo "Your compiler does not support '$CFLAG32' nor '$CFLAG64'.  Leaving ABI unset."
             fi
             rm -f foo foo.c
-        fi;;
+        fi
+
+        # Work around a bug in GCC 4.7.0 which breaks the build on Itanium CPUs:
+        # (Cf. #12765, #12751, and bug URL below.)
+        case "`uname -m`-`$CC -dumpversion 2>/dev/null`" in ia64-4.7.*)
+            # It's quite unlikely we match other compilers than GCC (e.g. clang) here.
+            required_cflags="$required_cflags -O0 -finline-functions -fschedule-insns"
+            echo >&2 "Warning: Disabling almost all optimization due to a bug in (at least)"
+            echo >&2 "         GCC 4.7.0 on Itanium, which otherwise would break the build."
+            echo >&2 "         See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=48496"
+            echo >&2 "         for current status and further details."
+            echo >&2 "         (And please report to e.g. sage-devel in case you feel this bug"
+            echo >&2 "          should already be fixed in GCC `$CC -dumpversion`.)"
+        esac
+        ;; # Linux
     CYGWIN)
         # Nothing special performed (yet).
         ;;
     *) # e.g. AIX or HP-UX
-        echo "Warning: Your platform ($UNAME) isn't yet explicitly supported" \
+        echo >&2 "Warning: Your platform ($UNAME) isn't yet explicitly supported" \
             "by this MPIR spkg, i.e., by Sage's part of it."
 esac
 
 export ABI CFLAGS CXXFLAGS # Partially redundant, but safe(r).
+# We don't export CPPFLAGS here, since we don't (have to) modify them.
+if [ -n "$required_ldflags" ]; then
+    export LDFLAGS # Probably redundant, but safe(r).
+fi
 
 ###############################################################################
 # Now configure MPIR, eventually modifying CFLAGS [further]:
 ###############################################################################
 
-cd src
+SAGE_CONF_OPTS="--enable-gmpcompat --enable-shared $SAGE_CONF_OPTS"
 
-
-SAGE_CONF_OPTS="--enable-gmpcompat --enable-cxx=yes $SAGE_CONF_OPTS"
-# Also build the static library to be used by e.g. ECM:
-# SAGE_CONF_OPTS="--enable-shared --disable-static $SAGE_CONF_OPTS"
-SAGE_CONF_OPTS="--enable-shared --enable-static $SAGE_CONF_OPTS"
+# If we're bootstrapping GCC from the GCC spkg, don't build the C++ interface
+# and static libraries in the first place (cf. #12782):
+if [ "$SAGE_BUILD_TOOLCHAIN" = yes ]; then
+    echo "Building a reduced version of MPIR to bootstrap GCC."
+    echo "MPIR will later get rebuilt (with the C++ interface and static libraries"
+    echo "enabled) using the new compiler."
+    SAGE_CONF_OPTS="--disable-cxx --disable-static $SAGE_CONF_OPTS"
+else
+    # Also build the static library to be used by e.g. ECM:
+    echo "Building MPIR with the C++ interface and (also) static libraries."
+    SAGE_CONF_OPTS="--enable-cxx --enable-static $SAGE_CONF_OPTS"
+fi
 # (Further options to 'configure' are added below.)
 
 
@@ -293,7 +378,7 @@
         echo "  CC:      $mpir_cc"
         echo "  CFLAGS:  $mpir_cflags"
     else
-        echo "Warning: Couldn't determine MPIR-selected CFLAGS from 'mpir.h'"
+        echo >&2 "Warning: Couldn't determine MPIR-selected CFLAGS from 'mpir.h'"
     fi
 else
     # We ignore errors in the first place, since we redirected all
@@ -314,13 +399,15 @@
 done
 
 echo "Settings required to properly build MPIR, taking into account SAGE_DEBUG etc.:"
-echo "  CFLAGS:  $required_cflags"
-echo "  LDFLAGS: $LDFLAGS" # Might be empty, or specified by the user.
-echo "  ABI:     $ABI" # Might be empty, or specified by the user.
+echo "  CFLAGS:  $required_cflags"  # Might be empty.
+echo "  LDFLAGS: $required_ldflags" # Might be empty.
+echo "  ABI:     $ABI" # Might be empty, or the one specified by the user.
 echo "Settings from the \"global\" environment:"
 echo "  CC:      $CC" # Set by Sage, maybe overridden by the user.
 echo "  CFLAGS:  $user_cflags"
-echo "  (CPPFLAGS, CXX and CXXFLAGS are listed below; these don't get modified.)"
+echo "  LDFLAGS: $user_ldflags"
+echo "  ABI:     $user_abi"
+echo "  (CPP, CPPFLAGS, CXX and CXXFLAGS are listed below; these don't get modified.)"
 
 if [ -z "$user_cflags" ]; then
     # No CFLAGS specified by user => Use either MPIR's, GMP's or our default
@@ -374,9 +461,12 @@
     fi
 fi
 
+LDFLAGS="$required_ldflags $user_ldflags"
+
 echo "Finally using the following settings:"
 echo "  CC=$CC"
 echo "  CFLAGS=$CFLAGS"
+echo "  CPP=$CPP"
 echo "  CPPFLAGS=$CPPFLAGS"
 echo "  CXX=$CXX"
 echo "  CXXFLAGS=$CXXFLAGS"
@@ -388,21 +478,24 @@
 # Now really configure MPIR with proper settings:
 ###############################################################################
 
+# We also add '--libdir="$SAGE_LOCAL/lib"' below, since newer autotools may
+# otherwise put the libraries into .../lib64 on 64-bit systems (cf. #12131).
+
 if [ -z "$MPIR_EXTRA_OPTS" ]; then
     echo "Configuring MPIR with the following options:"
-    echo "    --prefix=\"$SAGE_LOCAL\" $SAGE_CONF_OPTS"
+    echo "    --prefix=\"$SAGE_LOCAL\" --libdir=\"$SAGE_LOCAL/lib\" $SAGE_CONF_OPTS"
     echo "You can set MPIR_EXTRA_OPTS to pass additional parameters."
 else
     echo "Using additional 'configure' options as specified through" \
         "MPIR_EXTRA_OPTS:"
     echo "    $MPIR_EXTRA_OPTS"
     echo "Configuring MPIR with the following options:"
-    echo "    --prefix=\"$SAGE_LOCAL\" $SAGE_CONF_OPTS $MPIR_EXTRA_OPTS"
+    echo "    --prefix=\"$SAGE_LOCAL\" --libdir=\"$SAGE_LOCAL/lib\" $SAGE_CONF_OPTS $MPIR_EXTRA_OPTS"
 fi
 
-./configure --prefix="$SAGE_LOCAL" $SAGE_CONF_OPTS $MPIR_EXTRA_OPTS
+./configure --prefix="$SAGE_LOCAL" --libdir="$SAGE_LOCAL/lib" $SAGE_CONF_OPTS $MPIR_EXTRA_OPTS
 if [ $? -ne 0 ]; then
-    echo "Error configuring MPIR. (See above for the options passed to it.)"
+    echo >&2 "Error configuring MPIR. (See above for the options passed to it.)"
     exit 1
 fi
 
@@ -410,9 +503,10 @@
 # Now build MPIR:
 ###############################################################################
 
+echo "Now building MPIR..."
 $MAKE
 if [ $? -ne 0 ]; then
-    echo "Error building MPIR."
+    echo >&2 "Error building MPIR."
     exit 1
 fi
 
@@ -442,6 +536,7 @@
 # Now install MPIR:
 ###############################################################################
 
+echo "Now installing MPIR..."
 # The potential race condition in `make install` was fixed in MPIR 2.1.4.
 $MAKE install
 if [ $? -ne 0 ]; then
@@ -451,6 +546,7 @@
     fi
 fi
 
+echo
 echo "Remember to rebuild the Sage library ('./sage -b') such that it"
 echo "will use the new MPIR."
 echo "You may also have to (or want to) rebuild other Sage packages"
@@ -459,3 +555,4 @@
 echo "    cd $SAGE_ROOT"
 echo "    env SAGE_UPGRADING=yes make"
 echo "but note that this will usually take quite a lot of time."
+echo
