1 //===-- LeakDetector.cpp - Implement LeakDetector interface ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LeakDetector class.
12 //===----------------------------------------------------------------------===//
14 #include "Support/LeakDetector.h"
15 #include "llvm/Value.h"
22 struct LeakDetectorImpl {
23 LeakDetectorImpl(const char* const name) : Cache(0), Name(name) { }
25 // Because the most common usage pattern, by far, is to add a
26 // garbage object, then remove it immediately, we optimize this
27 // case. When an object is added, it is not added to the set
28 // immediately, it is added to the CachedValue Value. If it is
29 // immediately removed, no set search need be performed.
30 void addGarbage(const T* o) {
32 assert(Ts.count(Cache) == 0 && "Object already in set!");
38 void removeGarbage(const T* o) {
40 Cache = 0; // Cache hit
45 bool hasGarbage(const std::string& Message) {
46 addGarbage(0); // Flush the Cache
48 assert(Cache == 0 && "No value should be cached anymore!");
52 << "Leaked " << Name << " objects found: " << Message << ":\n\t";
53 std::copy(Ts.begin(), Ts.end(),
54 std::ostream_iterator<const T*>(std::cerr, " "));
57 // Clear out results so we don't get duplicate warnings on
66 std::set<const T*> Ts;
68 const char* const Name;
71 typedef LeakDetectorImpl<void> Objects;
72 typedef LeakDetectorImpl<Value> LLVMObjects;
74 Objects& getObjects() {
75 static Objects o("GENERIC");
79 LLVMObjects& getLLVMObjects() {
80 static LLVMObjects o("LLVM");
85 void LeakDetector::addGarbageObjectImpl(void *Object) {
86 getObjects().addGarbage(Object);
89 void LeakDetector::addGarbageObjectImpl(const Value *Object) {
90 getLLVMObjects().addGarbage(Object);
93 void LeakDetector::removeGarbageObjectImpl(void *Object) {
94 getObjects().removeGarbage(Object);
97 void LeakDetector::removeGarbageObjectImpl(const Value *Object) {
98 getLLVMObjects().removeGarbage(Object);
101 void LeakDetector::checkForGarbageImpl(const std::string &Message) {
102 // use non-short-circuit version so that both checks are performed
103 if (getObjects().hasGarbage(Message) |
104 getLLVMObjects().hasGarbage(Message))
105 std::cerr << "\nThis is probably because you removed an object, but didn't "
106 "delete it. Please check your code for memory leaks.\n";