Simplify memory management with std::unique_ptr.
[oota-llvm.git] / lib / Support / Timer.cpp
1 //===-- Timer.cpp - Interval Timing Support -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Interval Timing implementation.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Support/Timer.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/Format.h"
20 #include "llvm/Support/ManagedStatic.h"
21 #include "llvm/Support/Mutex.h"
22 #include "llvm/Support/Process.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace llvm;
25
26 // getLibSupportInfoOutputFilename - This ugly hack is brought to you courtesy
27 // of constructor/destructor ordering being unspecified by C++.  Basically the
28 // problem is that a Statistic object gets destroyed, which ends up calling
29 // 'GetLibSupportInfoOutputFile()' (below), which calls this function.
30 // LibSupportInfoOutputFilename used to be a global variable, but sometimes it
31 // would get destroyed before the Statistic, causing havoc to ensue.  We "fix"
32 // this by creating the string the first time it is needed and never destroying
33 // it.
34 static ManagedStatic<std::string> LibSupportInfoOutputFilename;
35 static std::string &getLibSupportInfoOutputFilename() {
36   return *LibSupportInfoOutputFilename;
37 }
38
39 static ManagedStatic<sys::SmartMutex<true> > TimerLock;
40
41 namespace {
42   static cl::opt<bool>
43   TrackSpace("track-memory", cl::desc("Enable -time-passes memory "
44                                       "tracking (this may be slow)"),
45              cl::Hidden);
46
47   static cl::opt<std::string, true>
48   InfoOutputFilename("info-output-file", cl::value_desc("filename"),
49                      cl::desc("File to append -stats and -timer output to"),
50                    cl::Hidden, cl::location(getLibSupportInfoOutputFilename()));
51 }
52
53 // Return a file stream to print our output on.
54 std::unique_ptr<raw_fd_ostream> llvm::CreateInfoOutputFile() {
55   const std::string &OutputFilename = getLibSupportInfoOutputFilename();
56   if (OutputFilename.empty())
57     return llvm::make_unique<raw_fd_ostream>(2, false); // stderr.
58   if (OutputFilename == "-")
59     return llvm::make_unique<raw_fd_ostream>(1, false); // stdout.
60
61   // Append mode is used because the info output file is opened and closed
62   // each time -stats or -time-passes wants to print output to it. To
63   // compensate for this, the test-suite Makefiles have code to delete the
64   // info output file before running commands which write to it.
65   std::error_code EC;
66   auto Result = llvm::make_unique<raw_fd_ostream>(
67       OutputFilename, EC, sys::fs::F_Append | sys::fs::F_Text);
68   if (!EC)
69     return Result;
70
71   errs() << "Error opening info-output-file '"
72     << OutputFilename << " for appending!\n";
73   return llvm::make_unique<raw_fd_ostream>(2, false); // stderr.
74 }
75
76
77 static TimerGroup *DefaultTimerGroup = nullptr;
78 static TimerGroup *getDefaultTimerGroup() {
79   TimerGroup *tmp = DefaultTimerGroup;
80   sys::MemoryFence();
81   if (tmp) return tmp;
82   
83   sys::SmartScopedLock<true> Lock(*TimerLock);
84   tmp = DefaultTimerGroup;
85   if (!tmp) {
86     tmp = new TimerGroup("Miscellaneous Ungrouped Timers");
87     sys::MemoryFence();
88     DefaultTimerGroup = tmp;
89   }
90
91   return tmp;
92 }
93
94 //===----------------------------------------------------------------------===//
95 // Timer Implementation
96 //===----------------------------------------------------------------------===//
97
98 void Timer::init(StringRef N) {
99   assert(!TG && "Timer already initialized");
100   Name.assign(N.begin(), N.end());
101   Started = false;
102   TG = getDefaultTimerGroup();
103   TG->addTimer(*this);
104 }
105
106 void Timer::init(StringRef N, TimerGroup &tg) {
107   assert(!TG && "Timer already initialized");
108   Name.assign(N.begin(), N.end());
109   Started = false;
110   TG = &tg;
111   TG->addTimer(*this);
112 }
113
114 Timer::~Timer() {
115   if (!TG) return;  // Never initialized, or already cleared.
116   TG->removeTimer(*this);
117 }
118
119 static inline size_t getMemUsage() {
120   if (!TrackSpace) return 0;
121   return sys::Process::GetMallocUsage();
122 }
123
124 TimeRecord TimeRecord::getCurrentTime(bool Start) {
125   TimeRecord Result;
126   sys::TimeValue now(0,0), user(0,0), sys(0,0);
127   
128   if (Start) {
129     Result.MemUsed = getMemUsage();
130     sys::Process::GetTimeUsage(now, user, sys);
131   } else {
132     sys::Process::GetTimeUsage(now, user, sys);
133     Result.MemUsed = getMemUsage();
134   }
135
136   Result.WallTime   =  now.seconds() +  now.microseconds() / 1000000.0;
137   Result.UserTime   = user.seconds() + user.microseconds() / 1000000.0;
138   Result.SystemTime =  sys.seconds() +  sys.microseconds() / 1000000.0;
139   return Result;
140 }
141
142 static ManagedStatic<std::vector<Timer*> > ActiveTimers;
143
144 void Timer::startTimer() {
145   Started = true;
146   ActiveTimers->push_back(this);
147   Time -= TimeRecord::getCurrentTime(true);
148 }
149
150 void Timer::stopTimer() {
151   Time += TimeRecord::getCurrentTime(false);
152
153   if (ActiveTimers->back() == this) {
154     ActiveTimers->pop_back();
155   } else {
156     std::vector<Timer*>::iterator I =
157       std::find(ActiveTimers->begin(), ActiveTimers->end(), this);
158     assert(I != ActiveTimers->end() && "stop but no startTimer?");
159     ActiveTimers->erase(I);
160   }
161 }
162
163 static void printVal(double Val, double Total, raw_ostream &OS) {
164   if (Total < 1e-7)   // Avoid dividing by zero.
165     OS << "        -----     ";
166   else
167     OS << format("  %7.4f (%5.1f%%)", Val, Val*100/Total);
168 }
169
170 void TimeRecord::print(const TimeRecord &Total, raw_ostream &OS) const {
171   if (Total.getUserTime())
172     printVal(getUserTime(), Total.getUserTime(), OS);
173   if (Total.getSystemTime())
174     printVal(getSystemTime(), Total.getSystemTime(), OS);
175   if (Total.getProcessTime())
176     printVal(getProcessTime(), Total.getProcessTime(), OS);
177   printVal(getWallTime(), Total.getWallTime(), OS);
178   
179   OS << "  ";
180   
181   if (Total.getMemUsed())
182     OS << format("%9" PRId64 "  ", (int64_t)getMemUsed());
183 }
184
185
186 //===----------------------------------------------------------------------===//
187 //   NamedRegionTimer Implementation
188 //===----------------------------------------------------------------------===//
189
190 namespace {
191
192 typedef StringMap<Timer> Name2TimerMap;
193
194 class Name2PairMap {
195   StringMap<std::pair<TimerGroup*, Name2TimerMap> > Map;
196 public:
197   ~Name2PairMap() {
198     for (StringMap<std::pair<TimerGroup*, Name2TimerMap> >::iterator
199          I = Map.begin(), E = Map.end(); I != E; ++I)
200       delete I->second.first;
201   }
202   
203   Timer &get(StringRef Name, StringRef GroupName) {
204     sys::SmartScopedLock<true> L(*TimerLock);
205     
206     std::pair<TimerGroup*, Name2TimerMap> &GroupEntry = Map[GroupName];
207     
208     if (!GroupEntry.first)
209       GroupEntry.first = new TimerGroup(GroupName);
210     
211     Timer &T = GroupEntry.second[Name];
212     if (!T.isInitialized())
213       T.init(Name, *GroupEntry.first);
214     return T;
215   }
216 };
217
218 }
219
220 static ManagedStatic<Name2TimerMap> NamedTimers;
221 static ManagedStatic<Name2PairMap> NamedGroupedTimers;
222
223 static Timer &getNamedRegionTimer(StringRef Name) {
224   sys::SmartScopedLock<true> L(*TimerLock);
225   
226   Timer &T = (*NamedTimers)[Name];
227   if (!T.isInitialized())
228     T.init(Name);
229   return T;
230 }
231
232 NamedRegionTimer::NamedRegionTimer(StringRef Name,
233                                    bool Enabled)
234   : TimeRegion(!Enabled ? nullptr : &getNamedRegionTimer(Name)) {}
235
236 NamedRegionTimer::NamedRegionTimer(StringRef Name, StringRef GroupName,
237                                    bool Enabled)
238   : TimeRegion(!Enabled ? nullptr : &NamedGroupedTimers->get(Name, GroupName)){}
239
240 //===----------------------------------------------------------------------===//
241 //   TimerGroup Implementation
242 //===----------------------------------------------------------------------===//
243
244 /// TimerGroupList - This is the global list of TimerGroups, maintained by the
245 /// TimerGroup ctor/dtor and is protected by the TimerLock lock.
246 static TimerGroup *TimerGroupList = nullptr;
247
248 TimerGroup::TimerGroup(StringRef name)
249   : Name(name.begin(), name.end()), FirstTimer(nullptr) {
250     
251   // Add the group to TimerGroupList.
252   sys::SmartScopedLock<true> L(*TimerLock);
253   if (TimerGroupList)
254     TimerGroupList->Prev = &Next;
255   Next = TimerGroupList;
256   Prev = &TimerGroupList;
257   TimerGroupList = this;
258 }
259
260 TimerGroup::~TimerGroup() {
261   // If the timer group is destroyed before the timers it owns, accumulate and
262   // print the timing data.
263   while (FirstTimer)
264     removeTimer(*FirstTimer);
265   
266   // Remove the group from the TimerGroupList.
267   sys::SmartScopedLock<true> L(*TimerLock);
268   *Prev = Next;
269   if (Next)
270     Next->Prev = Prev;
271 }
272
273
274 void TimerGroup::removeTimer(Timer &T) {
275   sys::SmartScopedLock<true> L(*TimerLock);
276   
277   // If the timer was started, move its data to TimersToPrint.
278   if (T.Started)
279     TimersToPrint.push_back(std::make_pair(T.Time, T.Name));
280
281   T.TG = nullptr;
282   
283   // Unlink the timer from our list.
284   *T.Prev = T.Next;
285   if (T.Next)
286     T.Next->Prev = T.Prev;
287   
288   // Print the report when all timers in this group are destroyed if some of
289   // them were started.
290   if (FirstTimer || TimersToPrint.empty())
291     return;
292
293   std::unique_ptr<raw_ostream> OutStream = CreateInfoOutputFile();
294   PrintQueuedTimers(*OutStream);
295 }
296
297 void TimerGroup::addTimer(Timer &T) {
298   sys::SmartScopedLock<true> L(*TimerLock);
299   
300   // Add the timer to our list.
301   if (FirstTimer)
302     FirstTimer->Prev = &T.Next;
303   T.Next = FirstTimer;
304   T.Prev = &FirstTimer;
305   FirstTimer = &T;
306 }
307
308 void TimerGroup::PrintQueuedTimers(raw_ostream &OS) {
309   // Sort the timers in descending order by amount of time taken.
310   std::sort(TimersToPrint.begin(), TimersToPrint.end());
311   
312   TimeRecord Total;
313   for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i)
314     Total += TimersToPrint[i].first;
315   
316   // Print out timing header.
317   OS << "===" << std::string(73, '-') << "===\n";
318   // Figure out how many spaces to indent TimerGroup name.
319   unsigned Padding = (80-Name.length())/2;
320   if (Padding > 80) Padding = 0;         // Don't allow "negative" numbers
321   OS.indent(Padding) << Name << '\n';
322   OS << "===" << std::string(73, '-') << "===\n";
323   
324   // If this is not an collection of ungrouped times, print the total time.
325   // Ungrouped timers don't really make sense to add up.  We still print the
326   // TOTAL line to make the percentages make sense.
327   if (this != DefaultTimerGroup)
328     OS << format("  Total Execution Time: %5.4f seconds (%5.4f wall clock)\n",
329                  Total.getProcessTime(), Total.getWallTime());
330   OS << '\n';
331   
332   if (Total.getUserTime())
333     OS << "   ---User Time---";
334   if (Total.getSystemTime())
335     OS << "   --System Time--";
336   if (Total.getProcessTime())
337     OS << "   --User+System--";
338   OS << "   ---Wall Time---";
339   if (Total.getMemUsed())
340     OS << "  ---Mem---";
341   OS << "  --- Name ---\n";
342   
343   // Loop through all of the timing data, printing it out.
344   for (unsigned i = 0, e = TimersToPrint.size(); i != e; ++i) {
345     const std::pair<TimeRecord, std::string> &Entry = TimersToPrint[e-i-1];
346     Entry.first.print(Total, OS);
347     OS << Entry.second << '\n';
348   }
349   
350   Total.print(Total, OS);
351   OS << "Total\n\n";
352   OS.flush();
353   
354   TimersToPrint.clear();
355 }
356
357 /// print - Print any started timers in this group and zero them.
358 void TimerGroup::print(raw_ostream &OS) {
359   sys::SmartScopedLock<true> L(*TimerLock);
360
361   // See if any of our timers were started, if so add them to TimersToPrint and
362   // reset them.
363   for (Timer *T = FirstTimer; T; T = T->Next) {
364     if (!T->Started) continue;
365     TimersToPrint.push_back(std::make_pair(T->Time, T->Name));
366     
367     // Clear out the time.
368     T->Started = 0;
369     T->Time = TimeRecord();
370   }
371
372   // If any timers were started, print the group.
373   if (!TimersToPrint.empty())
374     PrintQueuedTimers(OS);
375 }
376
377 /// printAll - This static method prints all timers and clears them all out.
378 void TimerGroup::printAll(raw_ostream &OS) {
379   sys::SmartScopedLock<true> L(*TimerLock);
380
381   for (TimerGroup *TG = TimerGroupList; TG; TG = TG->Next)
382     TG->print(OS);
383 }