blob: 1497f4e34082d520fa8b934691be0c34b9893f99 [file] [log] [blame]
Nick Lewycky4d0a9ff2011-11-14 20:50:16 +00001//===- llvm/unittest/Support/ManagedStatic.cpp - ManagedStatic tests ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9#include "llvm/Support/ManagedStatic.h"
Nick Lewyckyf7228f72011-11-14 22:10:23 +000010#include "llvm/Config/config.h"
Chandler Carruth5a88dda2012-12-04 10:23:08 +000011#include "llvm/Support/Threading.h"
Nick Lewyckyf7228f72011-11-14 22:10:23 +000012#ifdef HAVE_PTHREAD_H
Nick Lewycky4d0a9ff2011-11-14 20:50:16 +000013#include <pthread.h>
Nick Lewyckyf7228f72011-11-14 22:10:23 +000014#endif
Nick Lewycky4d0a9ff2011-11-14 20:50:16 +000015
16#include "gtest/gtest.h"
17
18using namespace llvm;
19
20namespace {
21
Duncan Sands8305acb2013-05-14 13:29:16 +000022#if LLVM_ENABLE_THREADS != 0 && defined(HAVE_PTHREAD_H) && \
23 !__has_feature(memory_sanitizer)
Nick Lewycky4d0a9ff2011-11-14 20:50:16 +000024namespace test1 {
25 llvm::ManagedStatic<int> ms;
26 void *helper(void*) {
27 *ms;
28 return NULL;
29 }
NAKAMURA Takumi91e22b02013-01-24 14:44:02 +000030
31 // Valgrind's leak checker complains glibc's stack allocation.
32 // To appease valgrind, we provide our own stack for each thread.
33 void *allocate_stack(pthread_attr_t &a, size_t n = 65536) {
34 void *stack = malloc(n);
35 pthread_attr_init(&a);
NAKAMURA Takumi41d35a32013-01-24 15:29:27 +000036#if defined(__linux__)
NAKAMURA Takumi91e22b02013-01-24 14:44:02 +000037 pthread_attr_setstack(&a, stack, n);
NAKAMURA Takumi41d35a32013-01-24 15:29:27 +000038#endif
NAKAMURA Takumi91e22b02013-01-24 14:44:02 +000039 return stack;
40 }
Nick Lewycky4d0a9ff2011-11-14 20:50:16 +000041}
42
43TEST(Initialize, MultipleThreads) {
44 // Run this test under tsan: http://code.google.com/p/data-race-test/
45
NAKAMURA Takumi91e22b02013-01-24 14:44:02 +000046 pthread_attr_t a1, a2;
47 void *p1 = test1::allocate_stack(a1);
48 void *p2 = test1::allocate_stack(a2);
49
Nick Lewycky4d0a9ff2011-11-14 20:50:16 +000050 llvm_start_multithreaded();
51 pthread_t t1, t2;
NAKAMURA Takumi91e22b02013-01-24 14:44:02 +000052 pthread_create(&t1, &a1, test1::helper, NULL);
53 pthread_create(&t2, &a2, test1::helper, NULL);
Nick Lewycky4d0a9ff2011-11-14 20:50:16 +000054 pthread_join(t1, NULL);
55 pthread_join(t2, NULL);
NAKAMURA Takumi91e22b02013-01-24 14:44:02 +000056 free(p1);
57 free(p2);
Nick Lewycky4d0a9ff2011-11-14 20:50:16 +000058 llvm_stop_multithreaded();
59}
Nick Lewyckyf7228f72011-11-14 22:10:23 +000060#endif
Nick Lewycky4d0a9ff2011-11-14 20:50:16 +000061
62} // anonymous namespace