From 59c4808db198385b4b37d7d36b36034e1849c600 Mon Sep 17 00:00:00 2001
From: Jelte Fennema <jelte.fennema@microsoft.com>
Date: Thu, 12 Aug 2021 16:32:35 +0200
Subject: [PATCH] Skip LLVM shutdown when bad exit

---
 src/backend/jit/llvm/llvmjit.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/src/backend/jit/llvm/llvmjit.c b/src/backend/jit/llvm/llvmjit.c
index 2bc6d549d3..cbb2d08b76 100644
--- a/src/backend/jit/llvm/llvmjit.c
+++ b/src/backend/jit/llvm/llvmjit.c
@@ -844,6 +844,18 @@ llvm_session_initialize(void)
 static void
 llvm_shutdown(int code, Datum arg)
 {
+	if (code != 0) {
+		/*
+		 * If we're exiting this process because of an error, it's possible
+		 * that the LLVM JIT is in a bad state. One example where this happens
+		 * is, because LLVM had an internal OOM. If we then try to cleanly
+		 * shut LLVM down, this can result into a segfault. So if this process
+		 * is not cleanly shutting down, we skip shutting down LLVM. Memory
+		 * will be released very soon anyway, since the process is planning to
+		 * exit.
+		 */
+		return;
+	}
 #if LLVM_VERSION_MAJOR > 11
 	{
 		if (llvm_opt3_orc)
-- 
2.17.1

