blob: 91ac9867a2855d83963fc6c35ee031b9485fdf8c [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2009 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "heap-profiler.h"
Steve Block3ce2e202009-11-05 08:53:23 +000031#include "frames-inl.h"
32#include "global-handles.h"
Kristian Monsen9dcf7e22010-06-28 14:14:28 +010033#include "profile-generator.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000034#include "string-stream.h"
35
36namespace v8 {
37namespace internal {
38
39
40#ifdef ENABLE_LOGGING_AND_PROFILING
41namespace {
42
43// Clusterizer is a set of helper functions for converting
44// object references into clusters.
45class Clusterizer : public AllStatic {
46 public:
47 static JSObjectsCluster Clusterize(HeapObject* obj) {
48 return Clusterize(obj, true);
49 }
50 static void InsertIntoTree(JSObjectsClusterTree* tree,
51 HeapObject* obj, bool fine_grain);
52 static void InsertReferenceIntoTree(JSObjectsClusterTree* tree,
53 const JSObjectsCluster& cluster) {
54 InsertIntoTree(tree, cluster, 0);
55 }
56
57 private:
58 static JSObjectsCluster Clusterize(HeapObject* obj, bool fine_grain);
59 static int CalculateNetworkSize(JSObject* obj);
60 static int GetObjectSize(HeapObject* obj) {
61 return obj->IsJSObject() ?
62 CalculateNetworkSize(JSObject::cast(obj)) : obj->Size();
63 }
64 static void InsertIntoTree(JSObjectsClusterTree* tree,
65 const JSObjectsCluster& cluster, int size);
66};
67
68
69JSObjectsCluster Clusterizer::Clusterize(HeapObject* obj, bool fine_grain) {
70 if (obj->IsJSObject()) {
71 JSObject* js_obj = JSObject::cast(obj);
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -080072 String* constructor = GetConstructorNameForHeapProfile(
73 JSObject::cast(js_obj));
Steve Blocka7e24c12009-10-30 11:49:00 +000074 // Differentiate Object and Array instances.
75 if (fine_grain && (constructor == Heap::Object_symbol() ||
76 constructor == Heap::Array_symbol())) {
77 return JSObjectsCluster(constructor, obj);
78 } else {
79 return JSObjectsCluster(constructor);
80 }
81 } else if (obj->IsString()) {
82 return JSObjectsCluster(Heap::String_symbol());
Steve Blockd0582a62009-12-15 09:54:21 +000083 } else if (obj->IsJSGlobalPropertyCell()) {
84 return JSObjectsCluster(JSObjectsCluster::GLOBAL_PROPERTY);
85 } else if (obj->IsCode() || obj->IsSharedFunctionInfo() || obj->IsScript()) {
86 return JSObjectsCluster(JSObjectsCluster::CODE);
Steve Blocka7e24c12009-10-30 11:49:00 +000087 }
88 return JSObjectsCluster();
89}
90
91
92void Clusterizer::InsertIntoTree(JSObjectsClusterTree* tree,
93 HeapObject* obj, bool fine_grain) {
94 JSObjectsCluster cluster = Clusterize(obj, fine_grain);
95 if (cluster.is_null()) return;
96 InsertIntoTree(tree, cluster, GetObjectSize(obj));
97}
98
99
100void Clusterizer::InsertIntoTree(JSObjectsClusterTree* tree,
101 const JSObjectsCluster& cluster, int size) {
102 JSObjectsClusterTree::Locator loc;
103 tree->Insert(cluster, &loc);
104 NumberAndSizeInfo number_and_size = loc.value();
105 number_and_size.increment_number(1);
106 number_and_size.increment_bytes(size);
107 loc.set_value(number_and_size);
108}
109
110
111int Clusterizer::CalculateNetworkSize(JSObject* obj) {
112 int size = obj->Size();
113 // If 'properties' and 'elements' are non-empty (thus, non-shared),
114 // take their size into account.
Iain Merrick75681382010-08-19 15:07:18 +0100115 if (obj->properties() != Heap::empty_fixed_array()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000116 size += obj->properties()->Size();
117 }
Iain Merrick75681382010-08-19 15:07:18 +0100118 if (obj->elements() != Heap::empty_fixed_array()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000119 size += obj->elements()->Size();
120 }
Steve Blockd0582a62009-12-15 09:54:21 +0000121 // For functions, also account non-empty context and literals sizes.
122 if (obj->IsJSFunction()) {
123 JSFunction* f = JSFunction::cast(obj);
124 if (f->unchecked_context()->IsContext()) {
125 size += f->context()->Size();
126 }
127 if (f->literals()->length() != 0) {
128 size += f->literals()->Size();
129 }
130 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000131 return size;
132}
133
134
135// A helper class for recording back references.
136class ReferencesExtractor : public ObjectVisitor {
137 public:
138 ReferencesExtractor(const JSObjectsCluster& cluster,
139 RetainerHeapProfile* profile)
140 : cluster_(cluster),
141 profile_(profile),
142 inside_array_(false) {
143 }
144
145 void VisitPointer(Object** o) {
Steve Blockd0582a62009-12-15 09:54:21 +0000146 if ((*o)->IsFixedArray() && !inside_array_) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000147 // Traverse one level deep for data members that are fixed arrays.
148 // This covers the case of 'elements' and 'properties' of JSObject,
149 // and function contexts.
150 inside_array_ = true;
151 FixedArray::cast(*o)->Iterate(this);
152 inside_array_ = false;
Steve Blockd0582a62009-12-15 09:54:21 +0000153 } else if ((*o)->IsHeapObject()) {
154 profile_->StoreReference(cluster_, HeapObject::cast(*o));
Steve Blocka7e24c12009-10-30 11:49:00 +0000155 }
156 }
157
158 void VisitPointers(Object** start, Object** end) {
159 for (Object** p = start; p < end; p++) VisitPointer(p);
160 }
161
162 private:
163 const JSObjectsCluster& cluster_;
164 RetainerHeapProfile* profile_;
165 bool inside_array_;
166};
167
168
169// A printer interface implementation for the Retainers profile.
170class RetainersPrinter : public RetainerHeapProfile::Printer {
171 public:
172 void PrintRetainers(const JSObjectsCluster& cluster,
173 const StringStream& retainers) {
174 HeapStringAllocator allocator;
175 StringStream stream(&allocator);
176 cluster.Print(&stream);
177 LOG(HeapSampleJSRetainersEvent(
178 *(stream.ToCString()), *(retainers.ToCString())));
179 }
180};
181
182
183// Visitor for printing a cluster tree.
184class ClusterTreePrinter BASE_EMBEDDED {
185 public:
186 explicit ClusterTreePrinter(StringStream* stream) : stream_(stream) {}
187 void Call(const JSObjectsCluster& cluster,
188 const NumberAndSizeInfo& number_and_size) {
189 Print(stream_, cluster, number_and_size);
190 }
191 static void Print(StringStream* stream,
192 const JSObjectsCluster& cluster,
193 const NumberAndSizeInfo& number_and_size);
194
195 private:
196 StringStream* stream_;
197};
198
199
200void ClusterTreePrinter::Print(StringStream* stream,
201 const JSObjectsCluster& cluster,
202 const NumberAndSizeInfo& number_and_size) {
203 stream->Put(',');
204 cluster.Print(stream);
205 stream->Add(";%d", number_and_size.number());
206}
207
208
209// Visitor for printing a retainer tree.
210class SimpleRetainerTreePrinter BASE_EMBEDDED {
211 public:
212 explicit SimpleRetainerTreePrinter(RetainerHeapProfile::Printer* printer)
213 : printer_(printer) {}
214 void Call(const JSObjectsCluster& cluster, JSObjectsClusterTree* tree);
215
216 private:
217 RetainerHeapProfile::Printer* printer_;
218};
219
220
221void SimpleRetainerTreePrinter::Call(const JSObjectsCluster& cluster,
222 JSObjectsClusterTree* tree) {
223 HeapStringAllocator allocator;
224 StringStream stream(&allocator);
225 ClusterTreePrinter retainers_printer(&stream);
226 tree->ForEach(&retainers_printer);
227 printer_->PrintRetainers(cluster, stream);
228}
229
230
231// Visitor for aggregating references count of equivalent clusters.
232class RetainersAggregator BASE_EMBEDDED {
233 public:
234 RetainersAggregator(ClustersCoarser* coarser, JSObjectsClusterTree* dest_tree)
235 : coarser_(coarser), dest_tree_(dest_tree) {}
236 void Call(const JSObjectsCluster& cluster,
237 const NumberAndSizeInfo& number_and_size);
238
239 private:
240 ClustersCoarser* coarser_;
241 JSObjectsClusterTree* dest_tree_;
242};
243
244
245void RetainersAggregator::Call(const JSObjectsCluster& cluster,
246 const NumberAndSizeInfo& number_and_size) {
247 JSObjectsCluster eq = coarser_->GetCoarseEquivalent(cluster);
248 if (eq.is_null()) eq = cluster;
249 JSObjectsClusterTree::Locator loc;
250 dest_tree_->Insert(eq, &loc);
251 NumberAndSizeInfo aggregated_number = loc.value();
252 aggregated_number.increment_number(number_and_size.number());
253 loc.set_value(aggregated_number);
254}
255
256
257// Visitor for printing retainers tree. Aggregates equivalent retainer clusters.
258class AggregatingRetainerTreePrinter BASE_EMBEDDED {
259 public:
260 AggregatingRetainerTreePrinter(ClustersCoarser* coarser,
261 RetainerHeapProfile::Printer* printer)
262 : coarser_(coarser), printer_(printer) {}
263 void Call(const JSObjectsCluster& cluster, JSObjectsClusterTree* tree);
264
265 private:
266 ClustersCoarser* coarser_;
267 RetainerHeapProfile::Printer* printer_;
268};
269
270
271void AggregatingRetainerTreePrinter::Call(const JSObjectsCluster& cluster,
272 JSObjectsClusterTree* tree) {
273 if (!coarser_->GetCoarseEquivalent(cluster).is_null()) return;
274 JSObjectsClusterTree dest_tree_;
275 RetainersAggregator retainers_aggregator(coarser_, &dest_tree_);
276 tree->ForEach(&retainers_aggregator);
277 HeapStringAllocator allocator;
278 StringStream stream(&allocator);
279 ClusterTreePrinter retainers_printer(&stream);
280 dest_tree_.ForEach(&retainers_printer);
281 printer_->PrintRetainers(cluster, stream);
282}
283
Steve Block791712a2010-08-27 10:21:07 +0100284} // namespace
285
Steve Blocka7e24c12009-10-30 11:49:00 +0000286
287// A helper class for building a retainers tree, that aggregates
288// all equivalent clusters.
Steve Block791712a2010-08-27 10:21:07 +0100289class RetainerTreeAggregator {
Steve Blocka7e24c12009-10-30 11:49:00 +0000290 public:
291 explicit RetainerTreeAggregator(ClustersCoarser* coarser)
292 : coarser_(coarser) {}
293 void Process(JSObjectsRetainerTree* input_tree) {
294 input_tree->ForEach(this);
295 }
296 void Call(const JSObjectsCluster& cluster, JSObjectsClusterTree* tree);
297 JSObjectsRetainerTree& output_tree() { return output_tree_; }
298
299 private:
300 ClustersCoarser* coarser_;
301 JSObjectsRetainerTree output_tree_;
302};
303
304
305void RetainerTreeAggregator::Call(const JSObjectsCluster& cluster,
306 JSObjectsClusterTree* tree) {
307 JSObjectsCluster eq = coarser_->GetCoarseEquivalent(cluster);
308 if (eq.is_null()) return;
309 JSObjectsRetainerTree::Locator loc;
310 if (output_tree_.Insert(eq, &loc)) {
311 loc.set_value(new JSObjectsClusterTree());
312 }
313 RetainersAggregator retainers_aggregator(coarser_, loc.value());
314 tree->ForEach(&retainers_aggregator);
315}
316
Steve Blocka7e24c12009-10-30 11:49:00 +0000317
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100318HeapProfiler* HeapProfiler::singleton_ = NULL;
319
320HeapProfiler::HeapProfiler()
321 : snapshots_(new HeapSnapshotsCollection()),
322 next_snapshot_uid_(1) {
323}
324
325
326HeapProfiler::~HeapProfiler() {
327 delete snapshots_;
328}
329
330#endif // ENABLE_LOGGING_AND_PROFILING
331
332void HeapProfiler::Setup() {
333#ifdef ENABLE_LOGGING_AND_PROFILING
334 if (singleton_ == NULL) {
335 singleton_ = new HeapProfiler();
336 }
337#endif
338}
339
340
341void HeapProfiler::TearDown() {
342#ifdef ENABLE_LOGGING_AND_PROFILING
343 delete singleton_;
344 singleton_ = NULL;
345#endif
346}
347
348
349#ifdef ENABLE_LOGGING_AND_PROFILING
350
Steve Block791712a2010-08-27 10:21:07 +0100351HeapSnapshot* HeapProfiler::TakeSnapshot(const char* name, int type) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100352 ASSERT(singleton_ != NULL);
Steve Block791712a2010-08-27 10:21:07 +0100353 return singleton_->TakeSnapshotImpl(name, type);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100354}
355
356
Steve Block791712a2010-08-27 10:21:07 +0100357HeapSnapshot* HeapProfiler::TakeSnapshot(String* name, int type) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100358 ASSERT(singleton_ != NULL);
Steve Block791712a2010-08-27 10:21:07 +0100359 return singleton_->TakeSnapshotImpl(name, type);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100360}
361
362
Steve Block791712a2010-08-27 10:21:07 +0100363HeapSnapshot* HeapProfiler::TakeSnapshotImpl(const char* name, int type) {
Iain Merrick75681382010-08-19 15:07:18 +0100364 Heap::CollectAllGarbage(true);
Steve Block791712a2010-08-27 10:21:07 +0100365 HeapSnapshot::Type s_type = static_cast<HeapSnapshot::Type>(type);
366 HeapSnapshot* result =
367 snapshots_->NewSnapshot(s_type, name, next_snapshot_uid_++);
368 switch (s_type) {
369 case HeapSnapshot::kFull: {
370 HeapSnapshotGenerator generator(result);
371 generator.GenerateSnapshot();
372 break;
373 }
374 case HeapSnapshot::kAggregated: {
375 AggregatedHeapSnapshot agg_snapshot;
376 AggregatedHeapSnapshotGenerator generator(&agg_snapshot);
377 generator.GenerateSnapshot();
378 generator.FillHeapSnapshot(result);
379 break;
380 }
381 default:
382 UNREACHABLE();
383 }
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100384 snapshots_->SnapshotGenerationFinished();
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100385 return result;
386}
387
388
Steve Block791712a2010-08-27 10:21:07 +0100389HeapSnapshot* HeapProfiler::TakeSnapshotImpl(String* name, int type) {
390 return TakeSnapshotImpl(snapshots_->GetName(name), type);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100391}
392
393
394int HeapProfiler::GetSnapshotsCount() {
395 ASSERT(singleton_ != NULL);
396 return singleton_->snapshots_->snapshots()->length();
397}
398
399
400HeapSnapshot* HeapProfiler::GetSnapshot(int index) {
401 ASSERT(singleton_ != NULL);
402 return singleton_->snapshots_->snapshots()->at(index);
403}
404
405
406HeapSnapshot* HeapProfiler::FindSnapshot(unsigned uid) {
407 ASSERT(singleton_ != NULL);
408 return singleton_->snapshots_->GetSnapshot(uid);
409}
410
411
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100412void HeapProfiler::ObjectMoveEvent(Address from, Address to) {
413 ASSERT(singleton_ != NULL);
414 singleton_->snapshots_->ObjectMoveEvent(from, to);
415}
416
417
Steve Blocka7e24c12009-10-30 11:49:00 +0000418const JSObjectsClusterTreeConfig::Key JSObjectsClusterTreeConfig::kNoKey;
419const JSObjectsClusterTreeConfig::Value JSObjectsClusterTreeConfig::kNoValue;
420
421
422ConstructorHeapProfile::ConstructorHeapProfile()
423 : zscope_(DELETE_ON_EXIT) {
424}
425
426
427void ConstructorHeapProfile::Call(const JSObjectsCluster& cluster,
428 const NumberAndSizeInfo& number_and_size) {
429 HeapStringAllocator allocator;
430 StringStream stream(&allocator);
431 cluster.Print(&stream);
432 LOG(HeapSampleJSConstructorEvent(*(stream.ToCString()),
433 number_and_size.number(),
434 number_and_size.bytes()));
435}
436
437
438void ConstructorHeapProfile::CollectStats(HeapObject* obj) {
439 Clusterizer::InsertIntoTree(&js_objects_info_tree_, obj, false);
440}
441
442
443void ConstructorHeapProfile::PrintStats() {
444 js_objects_info_tree_.ForEach(this);
445}
446
447
Steve Block3ce2e202009-11-05 08:53:23 +0000448static const char* GetConstructorName(const char* name) {
449 return name[0] != '\0' ? name : "(anonymous)";
450}
451
452
Steve Block791712a2010-08-27 10:21:07 +0100453const char* JSObjectsCluster::GetSpecialCaseName() const {
454 if (constructor_ == FromSpecialCase(ROOTS)) {
455 return "(roots)";
456 } else if (constructor_ == FromSpecialCase(GLOBAL_PROPERTY)) {
457 return "(global property)";
458 } else if (constructor_ == FromSpecialCase(CODE)) {
459 return "(code)";
460 } else if (constructor_ == FromSpecialCase(SELF)) {
461 return "(self)";
462 }
463 return NULL;
464}
465
466
Steve Blocka7e24c12009-10-30 11:49:00 +0000467void JSObjectsCluster::Print(StringStream* accumulator) const {
468 ASSERT(!is_null());
Steve Block791712a2010-08-27 10:21:07 +0100469 const char* special_case_name = GetSpecialCaseName();
470 if (special_case_name != NULL) {
471 accumulator->Add(special_case_name);
Steve Blocka7e24c12009-10-30 11:49:00 +0000472 } else {
473 SmartPointer<char> s_name(
474 constructor_->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL));
Steve Block3ce2e202009-11-05 08:53:23 +0000475 accumulator->Add("%s", GetConstructorName(*s_name));
Steve Blocka7e24c12009-10-30 11:49:00 +0000476 if (instance_ != NULL) {
477 accumulator->Add(":%p", static_cast<void*>(instance_));
478 }
479 }
480}
481
482
483void JSObjectsCluster::DebugPrint(StringStream* accumulator) const {
484 if (!is_null()) {
485 Print(accumulator);
486 } else {
487 accumulator->Add("(null cluster)");
488 }
489}
490
491
492inline ClustersCoarser::ClusterBackRefs::ClusterBackRefs(
493 const JSObjectsCluster& cluster_)
494 : cluster(cluster_), refs(kInitialBackrefsListCapacity) {
495}
496
497
498inline ClustersCoarser::ClusterBackRefs::ClusterBackRefs(
499 const ClustersCoarser::ClusterBackRefs& src)
500 : cluster(src.cluster), refs(src.refs.capacity()) {
501 refs.AddAll(src.refs);
502}
503
504
505inline ClustersCoarser::ClusterBackRefs&
506 ClustersCoarser::ClusterBackRefs::operator=(
507 const ClustersCoarser::ClusterBackRefs& src) {
508 if (this == &src) return *this;
509 cluster = src.cluster;
510 refs.Clear();
511 refs.AddAll(src.refs);
512 return *this;
513}
514
515
516inline int ClustersCoarser::ClusterBackRefs::Compare(
517 const ClustersCoarser::ClusterBackRefs& a,
518 const ClustersCoarser::ClusterBackRefs& b) {
519 int cmp = JSObjectsCluster::CompareConstructors(a.cluster, b.cluster);
520 if (cmp != 0) return cmp;
521 if (a.refs.length() < b.refs.length()) return -1;
522 if (a.refs.length() > b.refs.length()) return 1;
523 for (int i = 0; i < a.refs.length(); ++i) {
524 int cmp = JSObjectsCluster::Compare(a.refs[i], b.refs[i]);
525 if (cmp != 0) return cmp;
526 }
527 return 0;
528}
529
530
531ClustersCoarser::ClustersCoarser()
532 : zscope_(DELETE_ON_EXIT),
533 sim_list_(ClustersCoarser::kInitialSimilarityListCapacity),
534 current_pair_(NULL),
535 current_set_(NULL),
536 self_(NULL) {
537}
538
539
540void ClustersCoarser::Call(const JSObjectsCluster& cluster,
541 JSObjectsClusterTree* tree) {
542 if (!cluster.can_be_coarsed()) return;
543 ClusterBackRefs pair(cluster);
544 ASSERT(current_pair_ == NULL);
545 current_pair_ = &pair;
546 current_set_ = new JSObjectsRetainerTree();
547 self_ = &cluster;
548 tree->ForEach(this);
549 sim_list_.Add(pair);
550 current_pair_ = NULL;
551 current_set_ = NULL;
552 self_ = NULL;
553}
554
555
556void ClustersCoarser::Call(const JSObjectsCluster& cluster,
557 const NumberAndSizeInfo& number_and_size) {
558 ASSERT(current_pair_ != NULL);
559 ASSERT(current_set_ != NULL);
560 ASSERT(self_ != NULL);
561 JSObjectsRetainerTree::Locator loc;
562 if (JSObjectsCluster::Compare(*self_, cluster) == 0) {
563 current_pair_->refs.Add(JSObjectsCluster(JSObjectsCluster::SELF));
564 return;
565 }
566 JSObjectsCluster eq = GetCoarseEquivalent(cluster);
567 if (!eq.is_null()) {
568 if (current_set_->Find(eq, &loc)) return;
569 current_pair_->refs.Add(eq);
570 current_set_->Insert(eq, &loc);
571 } else {
572 current_pair_->refs.Add(cluster);
573 }
574}
575
576
577void ClustersCoarser::Process(JSObjectsRetainerTree* tree) {
578 int last_eq_clusters = -1;
579 for (int i = 0; i < kMaxPassesCount; ++i) {
580 sim_list_.Clear();
581 const int curr_eq_clusters = DoProcess(tree);
582 // If no new cluster equivalents discovered, abort processing.
583 if (last_eq_clusters == curr_eq_clusters) break;
584 last_eq_clusters = curr_eq_clusters;
585 }
586}
587
588
589int ClustersCoarser::DoProcess(JSObjectsRetainerTree* tree) {
590 tree->ForEach(this);
591 sim_list_.Iterate(ClusterBackRefs::SortRefsIterator);
592 sim_list_.Sort(ClusterBackRefsCmp);
593 return FillEqualityTree();
594}
595
596
597JSObjectsCluster ClustersCoarser::GetCoarseEquivalent(
598 const JSObjectsCluster& cluster) {
599 if (!cluster.can_be_coarsed()) return JSObjectsCluster();
600 EqualityTree::Locator loc;
601 return eq_tree_.Find(cluster, &loc) ? loc.value() : JSObjectsCluster();
602}
603
604
605bool ClustersCoarser::HasAnEquivalent(const JSObjectsCluster& cluster) {
606 // Return true for coarsible clusters that have a non-identical equivalent.
607 if (!cluster.can_be_coarsed()) return false;
608 JSObjectsCluster eq = GetCoarseEquivalent(cluster);
609 return !eq.is_null() && JSObjectsCluster::Compare(cluster, eq) != 0;
610}
611
612
613int ClustersCoarser::FillEqualityTree() {
614 int eq_clusters_count = 0;
615 int eq_to = 0;
616 bool first_added = false;
617 for (int i = 1; i < sim_list_.length(); ++i) {
618 if (ClusterBackRefs::Compare(sim_list_[i], sim_list_[eq_to]) == 0) {
619 EqualityTree::Locator loc;
620 if (!first_added) {
621 // Add self-equivalence, if we have more than one item in this
622 // equivalence class.
623 eq_tree_.Insert(sim_list_[eq_to].cluster, &loc);
624 loc.set_value(sim_list_[eq_to].cluster);
625 first_added = true;
626 }
627 eq_tree_.Insert(sim_list_[i].cluster, &loc);
628 loc.set_value(sim_list_[eq_to].cluster);
629 ++eq_clusters_count;
630 } else {
631 eq_to = i;
632 first_added = false;
633 }
634 }
635 return eq_clusters_count;
636}
637
638
639const JSObjectsCluster ClustersCoarser::ClusterEqualityConfig::kNoKey;
640const JSObjectsCluster ClustersCoarser::ClusterEqualityConfig::kNoValue;
641const JSObjectsRetainerTreeConfig::Key JSObjectsRetainerTreeConfig::kNoKey;
642const JSObjectsRetainerTreeConfig::Value JSObjectsRetainerTreeConfig::kNoValue =
643 NULL;
644
645
646RetainerHeapProfile::RetainerHeapProfile()
Steve Block791712a2010-08-27 10:21:07 +0100647 : zscope_(DELETE_ON_EXIT),
648 aggregator_(NULL) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000649 JSObjectsCluster roots(JSObjectsCluster::ROOTS);
650 ReferencesExtractor extractor(roots, this);
Steve Blockd0582a62009-12-15 09:54:21 +0000651 Heap::IterateRoots(&extractor, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +0000652}
653
654
Steve Block791712a2010-08-27 10:21:07 +0100655RetainerHeapProfile::~RetainerHeapProfile() {
656 delete aggregator_;
657}
658
659
Steve Blocka7e24c12009-10-30 11:49:00 +0000660void RetainerHeapProfile::StoreReference(const JSObjectsCluster& cluster,
661 HeapObject* ref) {
662 JSObjectsCluster ref_cluster = Clusterizer::Clusterize(ref);
Steve Blockd0582a62009-12-15 09:54:21 +0000663 if (ref_cluster.is_null()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +0000664 JSObjectsRetainerTree::Locator ref_loc;
665 if (retainers_tree_.Insert(ref_cluster, &ref_loc)) {
666 ref_loc.set_value(new JSObjectsClusterTree());
667 }
668 JSObjectsClusterTree* referenced_by = ref_loc.value();
669 Clusterizer::InsertReferenceIntoTree(referenced_by, cluster);
670}
671
672
673void RetainerHeapProfile::CollectStats(HeapObject* obj) {
Steve Blockd0582a62009-12-15 09:54:21 +0000674 const JSObjectsCluster cluster = Clusterizer::Clusterize(obj);
675 if (cluster.is_null()) return;
676 ReferencesExtractor extractor(cluster, this);
677 obj->Iterate(&extractor);
Steve Blocka7e24c12009-10-30 11:49:00 +0000678}
679
680
Steve Block791712a2010-08-27 10:21:07 +0100681void RetainerHeapProfile::CoarseAndAggregate() {
682 coarser_.Process(&retainers_tree_);
683 ASSERT(aggregator_ == NULL);
684 aggregator_ = new RetainerTreeAggregator(&coarser_);
685 aggregator_->Process(&retainers_tree_);
686}
687
688
Steve Blocka7e24c12009-10-30 11:49:00 +0000689void RetainerHeapProfile::DebugPrintStats(
690 RetainerHeapProfile::Printer* printer) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000691 // Print clusters that have no equivalents, aggregating their retainers.
692 AggregatingRetainerTreePrinter agg_printer(&coarser_, printer);
693 retainers_tree_.ForEach(&agg_printer);
Steve Block791712a2010-08-27 10:21:07 +0100694 // Print clusters that have equivalents.
Steve Blocka7e24c12009-10-30 11:49:00 +0000695 SimpleRetainerTreePrinter s_printer(printer);
Steve Block791712a2010-08-27 10:21:07 +0100696 aggregator_->output_tree().ForEach(&s_printer);
Steve Blocka7e24c12009-10-30 11:49:00 +0000697}
698
699
700void RetainerHeapProfile::PrintStats() {
701 RetainersPrinter printer;
702 DebugPrintStats(&printer);
703}
704
705
706//
707// HeapProfiler class implementation.
708//
Steve Block3ce2e202009-11-05 08:53:23 +0000709static void StackWeakReferenceCallback(Persistent<Value> object,
710 void* trace) {
711 DeleteArray(static_cast<Address*>(trace));
712 object.Dispose();
713}
714
715
716static void PrintProducerStackTrace(Object* obj, void* trace) {
717 if (!obj->IsJSObject()) return;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800718 String* constructor = GetConstructorNameForHeapProfile(JSObject::cast(obj));
Steve Block3ce2e202009-11-05 08:53:23 +0000719 SmartPointer<char> s_name(
720 constructor->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL));
721 LOG(HeapSampleJSProducerEvent(GetConstructorName(*s_name),
722 reinterpret_cast<Address*>(trace)));
Steve Blocka7e24c12009-10-30 11:49:00 +0000723}
724
725
726void HeapProfiler::WriteSample() {
727 LOG(HeapSampleBeginEvent("Heap", "allocated"));
728 LOG(HeapSampleStats(
Steve Block3ce2e202009-11-05 08:53:23 +0000729 "Heap", "allocated", Heap::CommittedMemory(), Heap::SizeOfObjects()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000730
Steve Block791712a2010-08-27 10:21:07 +0100731 AggregatedHeapSnapshot snapshot;
732 AggregatedHeapSnapshotGenerator generator(&snapshot);
733 generator.GenerateSnapshot();
Steve Blocka7e24c12009-10-30 11:49:00 +0000734
Steve Block791712a2010-08-27 10:21:07 +0100735 HistogramInfo* info = snapshot.info();
736 for (int i = FIRST_NONSTRING_TYPE;
737 i <= AggregatedHeapSnapshotGenerator::kAllStringsType;
738 ++i) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000739 if (info[i].bytes() > 0) {
740 LOG(HeapSampleItemEvent(info[i].name(), info[i].number(),
741 info[i].bytes()));
742 }
743 }
744
Steve Block791712a2010-08-27 10:21:07 +0100745 snapshot.js_cons_profile()->PrintStats();
746 snapshot.js_retainer_profile()->PrintStats();
Steve Blocka7e24c12009-10-30 11:49:00 +0000747
Steve Block3ce2e202009-11-05 08:53:23 +0000748 GlobalHandles::IterateWeakRoots(PrintProducerStackTrace,
749 StackWeakReferenceCallback);
750
Steve Blocka7e24c12009-10-30 11:49:00 +0000751 LOG(HeapSampleEndEvent("Heap", "allocated"));
752}
753
754
Steve Block791712a2010-08-27 10:21:07 +0100755AggregatedHeapSnapshot::AggregatedHeapSnapshot()
756 : info_(NewArray<HistogramInfo>(
757 AggregatedHeapSnapshotGenerator::kAllStringsType + 1)) {
758#define DEF_TYPE_NAME(name) info_[name].set_name(#name);
759 INSTANCE_TYPE_LIST(DEF_TYPE_NAME);
760#undef DEF_TYPE_NAME
761 info_[AggregatedHeapSnapshotGenerator::kAllStringsType].set_name(
762 "STRING_TYPE");
763}
764
765
766AggregatedHeapSnapshot::~AggregatedHeapSnapshot() {
767 DeleteArray(info_);
768}
769
770
771AggregatedHeapSnapshotGenerator::AggregatedHeapSnapshotGenerator(
772 AggregatedHeapSnapshot* agg_snapshot)
773 : agg_snapshot_(agg_snapshot) {
774}
775
776
777void AggregatedHeapSnapshotGenerator::CalculateStringsStats() {
778 HistogramInfo* info = agg_snapshot_->info();
779 HistogramInfo& strings = info[kAllStringsType];
780 // Lump all the string types together.
781#define INCREMENT_SIZE(type, size, name, camel_name) \
782 strings.increment_number(info[type].number()); \
783 strings.increment_bytes(info[type].bytes());
784 STRING_TYPE_LIST(INCREMENT_SIZE);
785#undef INCREMENT_SIZE
786}
787
788
789void AggregatedHeapSnapshotGenerator::CollectStats(HeapObject* obj) {
790 InstanceType type = obj->map()->instance_type();
791 ASSERT(0 <= type && type <= LAST_TYPE);
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800792 agg_snapshot_->info()[type].increment_number(1);
793 agg_snapshot_->info()[type].increment_bytes(obj->Size());
Steve Block791712a2010-08-27 10:21:07 +0100794}
795
796
797void AggregatedHeapSnapshotGenerator::GenerateSnapshot() {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800798 HeapIterator iterator(HeapIterator::kPreciseFiltering);
Steve Block791712a2010-08-27 10:21:07 +0100799 for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
800 CollectStats(obj);
801 agg_snapshot_->js_cons_profile()->CollectStats(obj);
802 agg_snapshot_->js_retainer_profile()->CollectStats(obj);
803 }
804 CalculateStringsStats();
805 agg_snapshot_->js_retainer_profile()->CoarseAndAggregate();
806}
807
808
809class CountingConstructorHeapProfileIterator {
810 public:
811 CountingConstructorHeapProfileIterator()
812 : entities_count_(0), children_count_(0) {
813 }
814
815 void Call(const JSObjectsCluster& cluster,
816 const NumberAndSizeInfo& number_and_size) {
817 ++entities_count_;
818 children_count_ += number_and_size.number();
819 }
820
821 int entities_count() { return entities_count_; }
822 int children_count() { return children_count_; }
823
824 private:
825 int entities_count_;
826 int children_count_;
827};
828
829
830static HeapEntry* AddEntryFromAggregatedSnapshot(HeapSnapshot* snapshot,
831 int* root_child_index,
832 HeapEntry::Type type,
833 const char* name,
834 int count,
835 int size,
836 int children_count,
837 int retainers_count) {
838 HeapEntry* entry = snapshot->AddEntry(
839 type, name, count, size, children_count, retainers_count);
840 ASSERT(entry != NULL);
841 snapshot->root()->SetUnidirElementReference(*root_child_index,
842 *root_child_index + 1,
843 entry);
844 *root_child_index = *root_child_index + 1;
845 return entry;
846}
847
848
849class AllocatingConstructorHeapProfileIterator {
850 public:
851 AllocatingConstructorHeapProfileIterator(HeapSnapshot* snapshot,
852 int* root_child_index)
853 : snapshot_(snapshot),
854 root_child_index_(root_child_index) {
855 }
856
857 void Call(const JSObjectsCluster& cluster,
858 const NumberAndSizeInfo& number_and_size) {
859 const char* name = cluster.GetSpecialCaseName();
860 if (name == NULL) {
861 name = snapshot_->collection()->GetFunctionName(cluster.constructor());
862 }
863 AddEntryFromAggregatedSnapshot(snapshot_,
864 root_child_index_,
865 HeapEntry::kObject,
866 name,
867 number_and_size.number(),
868 number_and_size.bytes(),
869 0,
870 0);
871 }
872
873 private:
874 HeapSnapshot* snapshot_;
875 int* root_child_index_;
876};
877
878
879static HeapObject* ClusterAsHeapObject(const JSObjectsCluster& cluster) {
880 return cluster.can_be_coarsed() ?
881 reinterpret_cast<HeapObject*>(cluster.instance()) : cluster.constructor();
882}
883
884
885static JSObjectsCluster HeapObjectAsCluster(HeapObject* object) {
886 if (object->IsString()) {
887 return JSObjectsCluster(String::cast(object));
888 } else {
889 JSObject* js_obj = JSObject::cast(object);
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800890 String* constructor = GetConstructorNameForHeapProfile(
891 JSObject::cast(js_obj));
Steve Block791712a2010-08-27 10:21:07 +0100892 return JSObjectsCluster(constructor, object);
893 }
894}
895
896
897class CountingRetainersIterator {
898 public:
899 CountingRetainersIterator(const JSObjectsCluster& child_cluster,
900 HeapEntriesMap* map)
901 : child_(ClusterAsHeapObject(child_cluster)), map_(map) {
902 if (map_->Map(child_) == NULL)
903 map_->Pair(child_, HeapEntriesMap::kHeapEntryPlaceholder);
904 }
905
906 void Call(const JSObjectsCluster& cluster,
907 const NumberAndSizeInfo& number_and_size) {
908 if (map_->Map(ClusterAsHeapObject(cluster)) == NULL)
909 map_->Pair(ClusterAsHeapObject(cluster),
910 HeapEntriesMap::kHeapEntryPlaceholder);
911 map_->CountReference(ClusterAsHeapObject(cluster), child_);
912 }
913
914 private:
915 HeapObject* child_;
916 HeapEntriesMap* map_;
917};
918
919
920class AllocatingRetainersIterator {
921 public:
922 AllocatingRetainersIterator(const JSObjectsCluster& child_cluster,
923 HeapEntriesMap* map)
924 : child_(ClusterAsHeapObject(child_cluster)), map_(map) {
925 child_entry_ = map_->Map(child_);
926 ASSERT(child_entry_ != NULL);
927 }
928
929 void Call(const JSObjectsCluster& cluster,
930 const NumberAndSizeInfo& number_and_size) {
931 int child_index, retainer_index;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800932 map_->CountReference(ClusterAsHeapObject(cluster),
933 child_,
934 &child_index,
935 &retainer_index);
936 map_->Map(ClusterAsHeapObject(cluster))->SetIndexedReference(
937 HeapGraphEdge::kElement,
938 child_index,
939 number_and_size.number(),
940 child_entry_,
941 retainer_index);
Steve Block791712a2010-08-27 10:21:07 +0100942 }
943
944 private:
945 HeapObject* child_;
946 HeapEntriesMap* map_;
947 HeapEntry* child_entry_;
948};
949
950
951template<class RetainersIterator>
952class AggregatingRetainerTreeIterator {
953 public:
954 explicit AggregatingRetainerTreeIterator(ClustersCoarser* coarser,
955 HeapEntriesMap* map)
956 : coarser_(coarser), map_(map) {
957 }
958
959 void Call(const JSObjectsCluster& cluster, JSObjectsClusterTree* tree) {
960 if (coarser_ != NULL &&
961 !coarser_->GetCoarseEquivalent(cluster).is_null()) return;
962 JSObjectsClusterTree* tree_to_iterate = tree;
963 ZoneScope zs(DELETE_ON_EXIT);
964 JSObjectsClusterTree dest_tree_;
965 if (coarser_ != NULL) {
966 RetainersAggregator retainers_aggregator(coarser_, &dest_tree_);
967 tree->ForEach(&retainers_aggregator);
968 tree_to_iterate = &dest_tree_;
969 }
970 RetainersIterator iterator(cluster, map_);
971 tree_to_iterate->ForEach(&iterator);
972 }
973
974 private:
975 ClustersCoarser* coarser_;
976 HeapEntriesMap* map_;
977};
978
979
980class AggregatedRetainerTreeAllocator {
981 public:
982 AggregatedRetainerTreeAllocator(HeapSnapshot* snapshot,
983 int* root_child_index)
984 : snapshot_(snapshot), root_child_index_(root_child_index) {
985 }
986
987 HeapEntry* GetEntry(
988 HeapObject* obj, int children_count, int retainers_count) {
989 JSObjectsCluster cluster = HeapObjectAsCluster(obj);
990 const char* name = cluster.GetSpecialCaseName();
991 if (name == NULL) {
992 name = snapshot_->collection()->GetFunctionName(cluster.constructor());
993 }
994 return AddEntryFromAggregatedSnapshot(
995 snapshot_, root_child_index_, HeapEntry::kObject, name,
996 0, 0, children_count, retainers_count);
997 }
998
999 private:
1000 HeapSnapshot* snapshot_;
1001 int* root_child_index_;
1002};
1003
1004
1005template<class Iterator>
1006void AggregatedHeapSnapshotGenerator::IterateRetainers(
1007 HeapEntriesMap* entries_map) {
1008 RetainerHeapProfile* p = agg_snapshot_->js_retainer_profile();
1009 AggregatingRetainerTreeIterator<Iterator> agg_ret_iter_1(
1010 p->coarser(), entries_map);
1011 p->retainers_tree()->ForEach(&agg_ret_iter_1);
1012 AggregatingRetainerTreeIterator<Iterator> agg_ret_iter_2(NULL, entries_map);
1013 p->aggregator()->output_tree().ForEach(&agg_ret_iter_2);
1014}
1015
1016
1017void AggregatedHeapSnapshotGenerator::FillHeapSnapshot(HeapSnapshot* snapshot) {
1018 // Count the number of entities.
1019 int histogram_entities_count = 0;
1020 int histogram_children_count = 0;
1021 int histogram_retainers_count = 0;
1022 for (int i = FIRST_NONSTRING_TYPE; i <= kAllStringsType; ++i) {
1023 if (agg_snapshot_->info()[i].bytes() > 0) {
1024 ++histogram_entities_count;
1025 }
1026 }
1027 CountingConstructorHeapProfileIterator counting_cons_iter;
1028 agg_snapshot_->js_cons_profile()->ForEach(&counting_cons_iter);
1029 histogram_entities_count += counting_cons_iter.entities_count();
1030 HeapEntriesMap entries_map;
1031 IterateRetainers<CountingRetainersIterator>(&entries_map);
1032 histogram_entities_count += entries_map.entries_count();
1033 histogram_children_count += entries_map.total_children_count();
1034 histogram_retainers_count += entries_map.total_retainers_count();
1035
1036 // Root entry references all other entries.
1037 histogram_children_count += histogram_entities_count;
1038 int root_children_count = histogram_entities_count;
1039 ++histogram_entities_count;
1040
1041 // Allocate and fill entries in the snapshot, allocate references.
1042 snapshot->AllocateEntries(histogram_entities_count,
1043 histogram_children_count,
1044 histogram_retainers_count);
1045 snapshot->AddEntry(HeapSnapshot::kInternalRootObject,
1046 root_children_count,
1047 0);
1048 int root_child_index = 0;
1049 for (int i = FIRST_NONSTRING_TYPE; i <= kAllStringsType; ++i) {
1050 if (agg_snapshot_->info()[i].bytes() > 0) {
1051 AddEntryFromAggregatedSnapshot(snapshot,
1052 &root_child_index,
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08001053 HeapEntry::kHidden,
Steve Block791712a2010-08-27 10:21:07 +01001054 agg_snapshot_->info()[i].name(),
1055 agg_snapshot_->info()[i].number(),
1056 agg_snapshot_->info()[i].bytes(),
1057 0,
1058 0);
1059 }
1060 }
1061 AllocatingConstructorHeapProfileIterator alloc_cons_iter(
1062 snapshot, &root_child_index);
1063 agg_snapshot_->js_cons_profile()->ForEach(&alloc_cons_iter);
1064 AggregatedRetainerTreeAllocator allocator(snapshot, &root_child_index);
1065 entries_map.UpdateEntries(&allocator);
1066
1067 // Fill up references.
1068 IterateRetainers<AllocatingRetainersIterator>(&entries_map);
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08001069
1070 snapshot->SetDominatorsToSelf();
Steve Block791712a2010-08-27 10:21:07 +01001071}
1072
1073
Steve Block3ce2e202009-11-05 08:53:23 +00001074bool ProducerHeapProfile::can_log_ = false;
1075
1076void ProducerHeapProfile::Setup() {
1077 can_log_ = true;
1078}
1079
Leon Clarkee46be812010-01-19 14:06:41 +00001080void ProducerHeapProfile::DoRecordJSObjectAllocation(Object* obj) {
1081 ASSERT(FLAG_log_producers);
1082 if (!can_log_) return;
Steve Block3ce2e202009-11-05 08:53:23 +00001083 int framesCount = 0;
1084 for (JavaScriptFrameIterator it; !it.done(); it.Advance()) {
1085 ++framesCount;
1086 }
1087 if (framesCount == 0) return;
1088 ++framesCount; // Reserve place for the terminator item.
1089 Vector<Address> stack(NewArray<Address>(framesCount), framesCount);
1090 int i = 0;
1091 for (JavaScriptFrameIterator it; !it.done(); it.Advance()) {
1092 stack[i++] = it.frame()->pc();
1093 }
1094 stack[i] = NULL;
1095 Handle<Object> handle = GlobalHandles::Create(obj);
1096 GlobalHandles::MakeWeak(handle.location(),
1097 static_cast<void*>(stack.start()),
1098 StackWeakReferenceCallback);
1099}
1100
1101
Steve Blocka7e24c12009-10-30 11:49:00 +00001102#endif // ENABLE_LOGGING_AND_PROFILING
1103
1104
1105} } // namespace v8::internal