1218885Sdim//===- llvm/Support/ThreadLocal.h - Thread Local Data ------------*- C++ -*-===//
2218885Sdim//
3218885Sdim//                     The LLVM Compiler Infrastructure
4218885Sdim//
5218885Sdim// This file is distributed under the University of Illinois Open Source
6218885Sdim// License. See LICENSE.TXT for details.
7218885Sdim//
8218885Sdim//===----------------------------------------------------------------------===//
9218885Sdim//
10218885Sdim// This file declares the llvm::sys::ThreadLocal class.
11218885Sdim//
12218885Sdim//===----------------------------------------------------------------------===//
13218885Sdim
14249423Sdim#ifndef LLVM_SUPPORT_THREADLOCAL_H
15249423Sdim#define LLVM_SUPPORT_THREADLOCAL_H
16218885Sdim
17249423Sdim#include "llvm/Support/DataTypes.h"
18218885Sdim#include "llvm/Support/Threading.h"
19218885Sdim#include <cassert>
20218885Sdim
21218885Sdimnamespace llvm {
22218885Sdim  namespace sys {
23218885Sdim    // ThreadLocalImpl - Common base class of all ThreadLocal instantiations.
24218885Sdim    // YOU SHOULD NEVER USE THIS DIRECTLY.
25218885Sdim    class ThreadLocalImpl {
26239462Sdim      typedef uint64_t ThreadLocalDataTy;
27239462Sdim      /// \brief Platform-specific thread local data.
28239462Sdim      ///
29239462Sdim      /// This is embedded in the class and we avoid malloc'ing/free'ing it,
30239462Sdim      /// to make this class more safe for use along with CrashRecoveryContext.
31239462Sdim      union {
32239462Sdim        char data[sizeof(ThreadLocalDataTy)];
33239462Sdim        ThreadLocalDataTy align_data;
34239462Sdim      };
35218885Sdim    public:
36218885Sdim      ThreadLocalImpl();
37218885Sdim      virtual ~ThreadLocalImpl();
38218885Sdim      void setInstance(const void* d);
39218885Sdim      const void* getInstance();
40218885Sdim      void removeInstance();
41218885Sdim    };
42218885Sdim
43218885Sdim    /// ThreadLocal - A class used to abstract thread-local storage.  It holds,
44218885Sdim    /// for each thread, a pointer a single object of type T.
45218885Sdim    template<class T>
46218885Sdim    class ThreadLocal : public ThreadLocalImpl {
47218885Sdim    public:
48218885Sdim      ThreadLocal() : ThreadLocalImpl() { }
49218885Sdim
50218885Sdim      /// get - Fetches a pointer to the object associated with the current
51218885Sdim      /// thread.  If no object has yet been associated, it returns NULL;
52218885Sdim      T* get() { return static_cast<T*>(getInstance()); }
53218885Sdim
54218885Sdim      // set - Associates a pointer to an object with the current thread.
55218885Sdim      void set(T* d) { setInstance(d); }
56218885Sdim
57218885Sdim      // erase - Removes the pointer associated with the current thread.
58218885Sdim      void erase() { removeInstance(); }
59218885Sdim    };
60218885Sdim  }
61218885Sdim}
62218885Sdim
63218885Sdim#endif
64