LLVM API Documentation
00001 //===---------------- ----LeaksContext.h - Implementation ------*- C++ -*--===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines various helper methods and classes used by 00011 // LLVMContextImpl for leaks detectors. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #include "llvm/Value.h" 00016 #include "llvm/Support/Streams.h" 00017 #include "llvm/ADT/SmallPtrSet.h" 00018 00019 using namespace llvm; 00020 00021 template <class T> 00022 struct PrinterTrait { 00023 static void print(const T* P) { cerr << P; } 00024 }; 00025 00026 template<> 00027 struct PrinterTrait<Value> { 00028 static void print(const Value* P) { cerr << *P; } 00029 }; 00030 00031 template <typename T> 00032 struct LeakDetectorImpl { 00033 explicit LeakDetectorImpl(const char* const name = "") : 00034 Cache(0), Name(name) { } 00035 00036 void clear() { 00037 Cache = 0; 00038 Ts.clear(); 00039 } 00040 00041 void setName(const char* n) { 00042 Name = n; 00043 } 00044 00045 // Because the most common usage pattern, by far, is to add a 00046 // garbage object, then remove it immediately, we optimize this 00047 // case. When an object is added, it is not added to the set 00048 // immediately, it is added to the CachedValue Value. If it is 00049 // immediately removed, no set search need be performed. 00050 void addGarbage(const T* o) { 00051 if (Cache) { 00052 assert(Ts.count(Cache) == 0 && "Object already in set!"); 00053 Ts.insert(Cache); 00054 } 00055 Cache = o; 00056 } 00057 00058 void removeGarbage(const T* o) { 00059 if (o == Cache) 00060 Cache = 0; // Cache hit 00061 else 00062 Ts.erase(o); 00063 } 00064 00065 bool hasGarbage(const std::string& Message) { 00066 addGarbage(0); // Flush the Cache 00067 00068 assert(Cache == 0 && "No value should be cached anymore!"); 00069 00070 if (!Ts.empty()) { 00071 cerr << "Leaked " << Name << " objects found: " << Message << ":\n"; 00072 for (typename SmallPtrSet<const T*, 8>::iterator I = Ts.begin(), 00073 E = Ts.end(); I != E; ++I) { 00074 cerr << "\t"; 00075 PrinterTrait<T>::print(*I); 00076 cerr << "\n"; 00077 } 00078 cerr << '\n'; 00079 00080 return true; 00081 } 00082 00083 return false; 00084 } 00085 00086 private: 00087 SmallPtrSet<const T*, 8> Ts; 00088 const T* Cache; 00089 const char* Name; 00090 };