-namespace {
- template <class T>
- struct VISIBILITY_HIDDEN PrinterTrait {
- static void print(const T* P) { llvm_cerr << P; }
- };
-
- template<>
- struct VISIBILITY_HIDDEN PrinterTrait<Value> {
- static void print(const Value* P) { llvm_cerr << *P; }
- };
-
- template <typename T>
- struct VISIBILITY_HIDDEN LeakDetectorImpl {
- LeakDetectorImpl(const char* const name) : Cache(0), Name(name) { }
-
- // Because the most common usage pattern, by far, is to add a
- // garbage object, then remove it immediately, we optimize this
- // case. When an object is added, it is not added to the set
- // immediately, it is added to the CachedValue Value. If it is
- // immediately removed, no set search need be performed.
- void addGarbage(const T* o) {
- if (Cache) {
- assert(Ts.count(Cache) == 0 && "Object already in set!");
- Ts.insert(Cache);
- }
- Cache = o;
- }
-
- void removeGarbage(const T* o) {
- if (o == Cache)
- Cache = 0; // Cache hit
- else
- Ts.erase(o);
- }
-
- bool hasGarbage(const std::string& Message) {
- addGarbage(0); // Flush the Cache
-
- assert(Cache == 0 && "No value should be cached anymore!");
-
- if (!Ts.empty()) {
- llvm_cerr
- << "Leaked " << Name << " objects found: " << Message << ":\n";
- for (typename std::set<const T*>::iterator I = Ts.begin(),
- E = Ts.end(); I != E; ++I) {
- llvm_cerr << "\t";
- PrinterTrait<T>::print(*I);
- llvm_cerr << "\n";
- }
- llvm_cerr << '\n';
-
- return true;
- }
- return false;
- }
-
- private:
- std::set<const T*> Ts;
- const T* Cache;
- const char* const Name;
- };
-
- LeakDetectorImpl<void> *Objects;
- LeakDetectorImpl<Value> *LLVMObjects;
-
- LeakDetectorImpl<void> &getObjects() {
- if (Objects == 0)
- Objects = new LeakDetectorImpl<void>("GENERIC");
- return *Objects;
- }
-
- LeakDetectorImpl<Value> &getLLVMObjects() {
- if (LLVMObjects == 0)
- LLVMObjects = new LeakDetectorImpl<Value>("LLVM");
- return *LLVMObjects;
- }