1 //===-- LeakDetector.cpp - Implement LeakDetector interface ---------------===//
3 // This file implements the LeakDetector class.
5 //===----------------------------------------------------------------------===//
7 #include "Support/LeakDetector.h"
8 #include "llvm/Value.h"
11 // Lazily allocate set so that release build doesn't have to do anything.
12 static std::set<const void*> *Objects = 0;
13 static std::set<const Value*> *LLVMObjects = 0;
15 // Because the most common usage pattern, by far, is to add a garbage object,
16 // then remove it immediately, we optimize this case. When an object is added,
17 // it is not added to the set immediately, it is added to the CachedValue Value.
18 // If it is immediately removed, no set search need be performed.
20 static const Value *CachedValue;
22 void LeakDetector::addGarbageObjectImpl(void *Object) {
24 Objects = new std::set<const void*>();
25 assert(Objects->count(Object) == 0 && "Object already in set!");
26 Objects->insert(Object);
29 void LeakDetector::removeGarbageObjectImpl(void *Object) {
31 Objects->erase(Object);
34 void LeakDetector::addGarbageObjectImpl(const Value *Object) {
37 LLVMObjects = new std::set<const Value*>();
38 assert(LLVMObjects->count(CachedValue) == 0 && "Object already in set!");
39 LLVMObjects->insert(CachedValue);
44 void LeakDetector::removeGarbageObjectImpl(const Value *Object) {
45 if (Object == CachedValue)
46 CachedValue = 0; // Cache hit!
48 LLVMObjects->erase(Object);
51 void LeakDetector::checkForGarbageImpl(const std::string &Message) {
52 if (CachedValue) // Flush the cache to the set...
53 addGarbageObjectImpl((Value*)0);
55 assert(CachedValue == 0 && "No value should be cached anymore!");
57 if ((Objects && !Objects->empty()) || (LLVMObjects && !LLVMObjects->empty())){
58 std::cerr << "Leaked objects found: " << Message << "\n";
60 if (Objects && !Objects->empty()) {
61 std::cerr << " Non-Value objects leaked:";
62 for (std::set<const void*>::iterator I = Objects->begin(),
63 E = Objects->end(); I != E; ++I)
64 std::cerr << " " << *I;
67 if (LLVMObjects && !LLVMObjects->empty()) {
68 std::cerr << " LLVM Value subclasses leaked:";
69 for (std::set<const Value*>::iterator I = LLVMObjects->begin(),
70 E = LLVMObjects->end(); I != E; ++I)
71 std::cerr << **I << "\n";
74 std::cerr << "This is probably because you removed an LLVM value "
75 << "(Instruction, BasicBlock, \netc), but didn't delete it. "
76 << "Please check your code for memory leaks.\n";
78 // Clear out results so we don't get duplicate warnings on next call...
79 delete Objects; delete LLVMObjects;
80 Objects = 0; LLVMObjects = 0;