1 //===-- LeakDetector.cpp - Implement LeakDetector interface ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LeakDetector class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/LeakDetector.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/IR/Metadata.h"
18 #include "llvm/IR/Value.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/ManagedStatic.h"
21 #include "llvm/Support/Mutex.h"
22 #include "llvm/Support/Threading.h"
25 static ManagedStatic<sys::SmartMutex<true> > ObjectsLock;
26 static ManagedStatic<LeakDetectorImpl<void> > Objects;
28 static void clearGarbage(LLVMContext &Context) {
30 Context.pImpl->LLVMObjects.clear();
33 void LeakDetector::addGarbageObjectImpl(void *Object) {
34 sys::SmartScopedLock<true> Lock(*ObjectsLock);
35 Objects->addGarbage(Object);
38 void LeakDetector::addGarbageObjectImpl(const Value *Object) {
39 LLVMContextImpl *pImpl = Object->getContext().pImpl;
40 pImpl->LLVMObjects.addGarbage(Object);
43 void LeakDetector::addGarbageObjectImpl(const MDNode *Object) {
44 LLVMContextImpl *pImpl = Object->getContext().pImpl;
45 pImpl->LLVMMDObjects.addGarbage(Object);
48 void LeakDetector::removeGarbageObjectImpl(void *Object) {
49 sys::SmartScopedLock<true> Lock(*ObjectsLock);
50 Objects->removeGarbage(Object);
53 void LeakDetector::removeGarbageObjectImpl(const Value *Object) {
54 LLVMContextImpl *pImpl = Object->getContext().pImpl;
55 pImpl->LLVMObjects.removeGarbage(Object);
58 void LeakDetector::removeGarbageObjectImpl(const MDNode *Object) {
59 LLVMContextImpl *pImpl = Object->getContext().pImpl;
60 pImpl->LLVMMDObjects.removeGarbage(Object);
63 void LeakDetector::checkForGarbageImpl(LLVMContext &Context,
64 const std::string &Message) {
65 LLVMContextImpl *pImpl = Context.pImpl;
66 sys::SmartScopedLock<true> Lock(*ObjectsLock);
68 Objects->setName("GENERIC");
69 pImpl->LLVMObjects.setName("LLVM");
70 pImpl->LLVMMDObjects.setName("LLVM-MD");
72 // use non-short-circuit version so that both checks are performed
73 if (Objects->hasGarbage(Message) |
74 pImpl->LLVMObjects.hasGarbage(Message) |
75 pImpl->LLVMMDObjects.hasGarbage(Message))
76 errs() << "\nThis is probably because you removed an object, but didn't "
77 << "delete it. Please check your code for memory leaks.\n";
79 // Clear out results so we don't get duplicate warnings on
81 clearGarbage(Context);