Index: llvm/lib/Support/Statistic.cpp =================================================================== --- llvm/lib/Support/Statistic.cpp +++ llvm/lib/Support/Statistic.cpp @@ -94,10 +94,20 @@ void Statistic::RegisterStatistic() { // If stats are enabled, inform StatInfo that this statistic should be // printed. - sys::SmartScopedLock Writer(*StatLock); + // There is a possible lock order inversion here. llvm_shutdown calls us + // while holding the ManagedStatic mutex. If we take StatLock and call + // ManagedStatic methods, we can end up taking the locks in the opposite + // order. To avoid that, we call all ManagedStatic methods before acquiring + // StatLock. if (!Initialized.load(std::memory_order_relaxed)) { + sys::SmartMutex &Lock = *StatLock; + StatisticInfo &SI = *StatInfo; + sys::SmartScopedLock Writer(Lock); + // Check Initialized again after acquiring the lock. + if (Initialized.load(std::memory_order_relaxed)) + return; if (Stats || Enabled) - StatInfo->addStatistic(this); + SI.addStatistic(this); // Remember we have been registered. Initialized.store(true, std::memory_order_release);