From 7573e40d57e15abca8a29f9907d29f2d4a97c119 Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@gmail.com>
Date: Wed, 4 Mar 2026 18:12:54 +1300
Subject: [PATCH v2 01/19] Provide PG_STACK_DIRECTION configuration macro.

General purpose systems capable of running PostgreSQL with stacks that
grow upwards rather down downwards don't seem to be found in the wild
these days.

Define a pg_config_manual.h variable that can be set to -1 or 1, to
remove runtime branching from stack-measuring code.  We could always add
feature detection if a new system shows up that wants the other setting,
but runtime doesn't make sense for a fixed properly of a system.

Though the existing user of that fact is very simple and doesn't save
much effort at all, a proposed patch would also like to know this at
compile time.
---
 src/backend/utils/misc/stack_depth.c | 10 ++++++++--
 src/include/pg_config_manual.h       |  8 ++++++++
 2 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/src/backend/utils/misc/stack_depth.c b/src/backend/utils/misc/stack_depth.c
index 61a07cf824e..3cd1b6f2336 100644
--- a/src/backend/utils/misc/stack_depth.c
+++ b/src/backend/utils/misc/stack_depth.c
@@ -118,9 +118,15 @@ stack_is_too_deep(void)
 
 	/*
 	 * Take abs value, since stacks grow up on some machines, down on others
+	 * (historical).  This formulation amounts to a no-op on modern systems.
 	 */
-	if (stack_depth < 0)
-		stack_depth = -stack_depth;
+	stack_depth *= -(PG_STACK_DIRECTION);
+
+	/*
+	 * If this assertion fails, either PG_STACK_DIRECTION is wrong or this
+	 * system doesn't have a traditional stack.
+	 */
+	Assert(stack_depth >= 0);
 
 	/*
 	 * Trouble?
diff --git a/src/include/pg_config_manual.h b/src/include/pg_config_manual.h
index 521b49b8888..75035b9e796 100644
--- a/src/include/pg_config_manual.h
+++ b/src/include/pg_config_manual.h
@@ -222,6 +222,14 @@
  */
 #define PG_IO_ALIGN_SIZE		4096
 
+/*
+ * Historical systems had stacks that grew upwards in address space, but none
+ * of them remain.  Our stack depth-checking code no longer wastes cycles
+ * considering that possibility at runtime.  It assumes (but also asserts)
+ * that the stack grows in the direction defined here: -1 or +1.
+ */
+#define PG_STACK_DIRECTION -1
+
 /*
  *------------------------------------------------------------------------
  * The following symbols are for enabling debugging code, not for
-- 
2.53.0

