Path: blob/main/contrib/llvm-project/clang/lib/Basic/Stack.cpp
35232 views
//===--- Stack.cpp - Utilities for dealing with stack space ---------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7///8/// \file9/// Defines utilities for dealing with stack allocation and stack space.10///11//===----------------------------------------------------------------------===//1213#include "clang/Basic/Stack.h"14#include "llvm/Support/CrashRecoveryContext.h"1516#ifdef _MSC_VER17#include <intrin.h> // for _AddressOfReturnAddress18#endif1920static LLVM_THREAD_LOCAL void *BottomOfStack = nullptr;2122static void *getStackPointer() {23#if __GNUC__ || __has_builtin(__builtin_frame_address)24return __builtin_frame_address(0);25#elif defined(_MSC_VER)26return _AddressOfReturnAddress();27#else28char CharOnStack = 0;29// The volatile store here is intended to escape the local variable, to30// prevent the compiler from optimizing CharOnStack into anything other31// than a char on the stack.32//33// Tested on: MSVC 2015 - 2019, GCC 4.9 - 9, Clang 3.2 - 9, ICC 13 - 19.34char *volatile Ptr = &CharOnStack;35return Ptr;36#endif37}3839void clang::noteBottomOfStack() {40if (!BottomOfStack)41BottomOfStack = getStackPointer();42}4344bool clang::isStackNearlyExhausted() {45// We consider 256 KiB to be sufficient for any code that runs between checks46// for stack size.47constexpr size_t SufficientStack = 256 << 10;4849// If we don't know where the bottom of the stack is, hope for the best.50if (!BottomOfStack)51return false;5253intptr_t StackDiff = (intptr_t)getStackPointer() - (intptr_t)BottomOfStack;54size_t StackUsage = (size_t)std::abs(StackDiff);5556// If the stack pointer has a surprising value, we do not understand this57// stack usage scheme. (Perhaps the target allocates new stack regions on58// demand for us.) Don't try to guess what's going on.59if (StackUsage > DesiredStackSize)60return false;6162return StackUsage >= DesiredStackSize - SufficientStack;63}6465void clang::runWithSufficientStackSpaceSlow(llvm::function_ref<void()> Diag,66llvm::function_ref<void()> Fn) {67llvm::CrashRecoveryContext CRC;68CRC.RunSafelyOnThread([&] {69noteBottomOfStack();70Diag();71Fn();72}, DesiredStackSize);73}747576