1 /*
   2  * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classLoader.hpp"
  27 #include "code/codeCache.hpp"
  28 #include "code/vtableStubs.hpp"
  29 #include "gc_interface/collectedHeap.inline.hpp"
  30 #include "interpreter/interpreter.hpp"
  31 #include "memory/allocation.inline.hpp"
  32 #include "memory/universe.inline.hpp"
  33 #include "oops/oop.inline.hpp"
  34 #include "oops/oop.inline2.hpp"
  35 #include "oops/symbol.hpp"
  36 #include "runtime/deoptimization.hpp"
  37 #include "runtime/fprofiler.hpp"
  38 #include "runtime/mutexLocker.hpp"
  39 #include "runtime/stubCodeGenerator.hpp"
  40 #include "runtime/stubRoutines.hpp"
  41 #include "runtime/task.hpp"
  42 #include "runtime/thread.inline.hpp"
  43 #include "runtime/vframe.hpp"
  44 #include "utilities/macros.hpp"
  45 
  46 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  47 
  48 // Static fields of FlatProfiler
  49 int               FlatProfiler::received_gc_ticks   = 0;
  50 int               FlatProfiler::vm_operation_ticks  = 0;
  51 int               FlatProfiler::threads_lock_ticks  = 0;
  52 int               FlatProfiler::class_loader_ticks  = 0;
  53 int               FlatProfiler::extra_ticks         = 0;
  54 int               FlatProfiler::blocked_ticks       = 0;
  55 int               FlatProfiler::deopt_ticks         = 0;
  56 int               FlatProfiler::unknown_ticks       = 0;
  57 int               FlatProfiler::interpreter_ticks   = 0;
  58 int               FlatProfiler::compiler_ticks      = 0;
  59 int               FlatProfiler::received_ticks      = 0;
  60 int               FlatProfiler::delivered_ticks     = 0;
  61 int*              FlatProfiler::bytecode_ticks      = NULL;
  62 int*              FlatProfiler::bytecode_ticks_stub = NULL;
  63 int               FlatProfiler::all_int_ticks       = 0;
  64 int               FlatProfiler::all_comp_ticks      = 0;
  65 int               FlatProfiler::all_ticks           = 0;
  66 bool              FlatProfiler::full_profile_flag   = false;
  67 ThreadProfiler*   FlatProfiler::thread_profiler     = NULL;
  68 ThreadProfiler*   FlatProfiler::vm_thread_profiler  = NULL;
  69 FlatProfilerTask* FlatProfiler::task                = NULL;
  70 elapsedTimer      FlatProfiler::timer;
  71 int               FlatProfiler::interval_ticks_previous = 0;
  72 IntervalData*     FlatProfiler::interval_data       = NULL;
  73 
  74 ThreadProfiler::ThreadProfiler() {
  75   // Space for the ProfilerNodes
  76   const int area_size = 1 * ProfilerNodeSize * 1024;
  77   area_bottom = AllocateHeap(area_size, mtInternal);
  78   area_top    = area_bottom;
  79   area_limit  = area_bottom + area_size;
  80 
  81   // ProfilerNode pointer table
  82   table = NEW_C_HEAP_ARRAY(ProfilerNode*, table_size, mtInternal);
  83   initialize();
  84   engaged = false;
  85 }
  86 
  87 ThreadProfiler::~ThreadProfiler() {
  88   FreeHeap(area_bottom);
  89   area_bottom = NULL;
  90   area_top = NULL;
  91   area_limit = NULL;
  92   FreeHeap(table);
  93   table = NULL;
  94 }
  95 
  96 // Statics for ThreadProfiler
  97 int ThreadProfiler::table_size = 1024;
  98 
  99 int ThreadProfiler::entry(int  value) {
 100   value = (value > 0) ? value : -value;
 101   return value % table_size;
 102 }
 103 
 104 ThreadProfilerMark::ThreadProfilerMark(ThreadProfilerMark::Region r) {
 105   _r = r;
 106   _pp = NULL;
 107   assert(((r > ThreadProfilerMark::noRegion) && (r < ThreadProfilerMark::maxRegion)), "ThreadProfilerMark::Region out of bounds");
 108   Thread* tp = Thread::current();
 109   if (tp != NULL && tp->is_Java_thread()) {
 110     JavaThread* jtp = (JavaThread*) tp;
 111     ThreadProfiler* pp = jtp->get_thread_profiler();
 112     _pp = pp;
 113     if (pp != NULL) {
 114       pp->region_flag[r] = true;
 115     }
 116   }
 117 }
 118 
 119 ThreadProfilerMark::~ThreadProfilerMark() {
 120   if (_pp != NULL) {
 121     _pp->region_flag[_r] = false;
 122   }
 123   _pp = NULL;
 124 }
 125 
 126 // Random other statics
 127 static const int col1 = 2;      // position of output column 1
 128 static const int col2 = 11;     // position of output column 2
 129 static const int col3 = 25;     // position of output column 3
 130 static const int col4 = 55;     // position of output column 4
 131 
 132 
 133 // Used for detailed profiling of nmethods.
 134 class PCRecorder : AllStatic {
 135  private:
 136   static int*    counters;
 137   static address base;
 138   enum {
 139    bucket_size = 16
 140   };
 141   static int     index_for(address pc) { return (pc - base)/bucket_size;   }
 142   static address pc_for(int index)     { return base + (index * bucket_size); }
 143   static int     size() {
 144     return ((int)CodeCache::max_capacity())/bucket_size * BytesPerWord;
 145   }
 146  public:
 147   static address bucket_start_for(address pc) {
 148     if (counters == NULL) return NULL;
 149     return pc_for(index_for(pc));
 150   }
 151   static int bucket_count_for(address pc)  { return counters[index_for(pc)]; }
 152   static void init();
 153   static void record(address pc);
 154   static void print();
 155   static void print_blobs(CodeBlob* cb);
 156 };
 157 
 158 int*    PCRecorder::counters = NULL;
 159 address PCRecorder::base     = NULL;
 160 
 161 void PCRecorder::init() {
 162   MutexLockerEx lm(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 163   int s = size();
 164   counters = NEW_C_HEAP_ARRAY(int, s, mtInternal);
 165   for (int index = 0; index < s; index++) {
 166     counters[index] = 0;
 167   }
 168   base = CodeCache::first_address();
 169 }
 170 
 171 void PCRecorder::record(address pc) {
 172   if (counters == NULL) return;
 173   assert(CodeCache::contains(pc), "must be in CodeCache");
 174   counters[index_for(pc)]++;
 175 }
 176 
 177 
 178 address FlatProfiler::bucket_start_for(address pc) {
 179   return PCRecorder::bucket_start_for(pc);
 180 }
 181 
 182 int FlatProfiler::bucket_count_for(address pc) {
 183   return PCRecorder::bucket_count_for(pc);
 184 }
 185 
 186 void PCRecorder::print() {
 187   if (counters == NULL) return;
 188 
 189   tty->cr();
 190   tty->print_cr("Printing compiled methods with PC buckets having more than %d ticks", ProfilerPCTickThreshold);
 191   tty->print_cr("===================================================================");
 192   tty->cr();
 193 
 194   GrowableArray<CodeBlob*>* candidates = new GrowableArray<CodeBlob*>(20);
 195 
 196 
 197   int s;
 198   {
 199     MutexLockerEx lm(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 200     s = size();
 201   }
 202 
 203   for (int index = 0; index < s; index++) {
 204     int count = counters[index];
 205     if (count > ProfilerPCTickThreshold) {
 206       address pc = pc_for(index);
 207       CodeBlob* cb = CodeCache::find_blob_unsafe(pc);
 208       if (cb != NULL && candidates->find(cb) < 0) {
 209         candidates->push(cb);
 210       }
 211     }
 212   }
 213   for (int i = 0; i < candidates->length(); i++) {
 214     print_blobs(candidates->at(i));
 215   }
 216 }
 217 
 218 void PCRecorder::print_blobs(CodeBlob* cb) {
 219   if (cb != NULL) {
 220     cb->print();
 221     if (cb->is_nmethod()) {
 222       ((nmethod*)cb)->print_code();
 223     }
 224     tty->cr();
 225   } else {
 226     tty->print_cr("stub code");
 227   }
 228 }
 229 
 230 class tick_counter {            // holds tick info for one node
 231  public:
 232   int ticks_in_code;
 233   int ticks_in_native;
 234 
 235   tick_counter()                     {  ticks_in_code = ticks_in_native = 0; }
 236   tick_counter(int code, int native) {  ticks_in_code = code; ticks_in_native = native; }
 237 
 238   int total() const {
 239     return (ticks_in_code + ticks_in_native);
 240   }
 241 
 242   void add(tick_counter* a) {
 243     ticks_in_code += a->ticks_in_code;
 244     ticks_in_native += a->ticks_in_native;
 245   }
 246 
 247   void update(TickPosition where) {
 248     switch(where) {
 249       case tp_code:     ticks_in_code++;       break;
 250       case tp_native:   ticks_in_native++;      break;
 251     }
 252   }
 253 
 254   void print_code(outputStream* st, int total_ticks) {
 255     st->print("%5.1f%% %5d ", total() * 100.0 / total_ticks, ticks_in_code);
 256   }
 257 
 258   void print_native(outputStream* st) {
 259     st->print(" + %5d ", ticks_in_native);
 260   }
 261 };
 262 
 263 class ProfilerNode {
 264  private:
 265   ProfilerNode* _next;
 266  public:
 267   tick_counter ticks;
 268 
 269  public:
 270 
 271   void* operator new(size_t size, ThreadProfiler* tp) throw();
 272   void  operator delete(void* p);
 273 
 274   ProfilerNode() {
 275     _next = NULL;
 276   }
 277 
 278   virtual ~ProfilerNode() {
 279     if (_next)
 280       delete _next;
 281   }
 282 
 283   void set_next(ProfilerNode* n) { _next = n; }
 284   ProfilerNode* next()           { return _next; }
 285 
 286   void update(TickPosition where) { ticks.update(where);}
 287   int total_ticks() { return ticks.total(); }
 288 
 289   virtual bool is_interpreted() const { return false; }
 290   virtual bool is_compiled()    const { return false; }
 291   virtual bool is_stub()        const { return false; }
 292   virtual bool is_runtime_stub() const{ return false; }
 293   virtual void oops_do(OopClosure* f) = 0;
 294 
 295   virtual bool interpreted_match(Method* m) const { return false; }
 296   virtual bool compiled_match(Method* m ) const { return false; }
 297   virtual bool stub_match(Method* m, const char* name) const { return false; }
 298   virtual bool adapter_match() const { return false; }
 299   virtual bool runtimeStub_match(const CodeBlob* stub, const char* name) const { return false; }
 300   virtual bool unknown_compiled_match(const CodeBlob* cb) const { return false; }
 301 
 302   static void print_title(outputStream* st) {
 303     st->print(" + native");
 304     st->fill_to(col3);
 305     st->print("Method");
 306     st->fill_to(col4);
 307     st->cr();
 308   }
 309 
 310   static void print_total(outputStream* st, tick_counter* t, int total, const char* msg) {
 311     t->print_code(st, total);
 312     st->fill_to(col2);
 313     t->print_native(st);
 314     st->fill_to(col3);
 315     st->print("%s", msg);
 316     st->cr();
 317   }
 318 
 319   virtual Method* method()         = 0;
 320 
 321   virtual void print_method_on(outputStream* st) {
 322     int limit;
 323     int i;
 324     Method* m = method();
 325     Symbol* k = m->klass_name();
 326     // Print the class name with dots instead of slashes
 327     limit = k->utf8_length();
 328     for (i = 0 ; i < limit ; i += 1) {
 329       char c = (char) k->byte_at(i);
 330       if (c == '/') {
 331         c = '.';
 332       }
 333       st->print("%c", c);
 334     }
 335     if (limit > 0) {
 336       st->print(".");
 337     }
 338     Symbol* n = m->name();
 339     limit = n->utf8_length();
 340     for (i = 0 ; i < limit ; i += 1) {
 341       char c = (char) n->byte_at(i);
 342       st->print("%c", c);
 343     }
 344     if (Verbose || WizardMode) {
 345       // Disambiguate overloaded methods
 346       Symbol* sig = m->signature();
 347       sig->print_symbol_on(st);
 348     } else if (MethodHandles::is_signature_polymorphic(m->intrinsic_id()))
 349       // compare with Method::print_short_name
 350       MethodHandles::print_as_basic_type_signature_on(st, m->signature(), true);
 351   }
 352 
 353   virtual void print(outputStream* st, int total_ticks) {
 354     ticks.print_code(st, total_ticks);
 355     st->fill_to(col2);
 356     ticks.print_native(st);
 357     st->fill_to(col3);
 358     print_method_on(st);
 359     st->cr();
 360   }
 361 
 362   // for hashing into the table
 363   static int hash(Method* method) {
 364       // The point here is to try to make something fairly unique
 365       // out of the fields we can read without grabbing any locks
 366       // since the method may be locked when we need the hash.
 367       return (
 368           method->code_size() ^
 369           method->max_stack() ^
 370           method->max_locals() ^
 371           method->size_of_parameters());
 372   }
 373 
 374   // for sorting
 375   static int compare(ProfilerNode** a, ProfilerNode** b) {
 376     return (*b)->total_ticks() - (*a)->total_ticks();
 377   }
 378 };
 379 
 380 void* ProfilerNode::operator new(size_t size, ThreadProfiler* tp) throw() {
 381   void* result = (void*) tp->area_top;
 382   tp->area_top += size;
 383 
 384   if (tp->area_top > tp->area_limit) {
 385     fatal("flat profiler buffer overflow");
 386   }
 387   return result;
 388 }
 389 
 390 void ProfilerNode::operator delete(void* p){
 391 }
 392 
 393 class interpretedNode : public ProfilerNode {
 394  private:
 395    Method* _method;
 396    oop       _class_loader;  // needed to keep metadata for the method alive
 397  public:
 398    interpretedNode(Method* method, TickPosition where) : ProfilerNode() {
 399      _method = method;
 400      _class_loader = method->method_holder()->class_loader();
 401      update(where);
 402    }
 403 
 404    bool is_interpreted() const { return true; }
 405 
 406    bool interpreted_match(Method* m) const {
 407       return _method == m;
 408    }
 409 
 410    void oops_do(OopClosure* f) {
 411      f->do_oop(&_class_loader);
 412    }
 413 
 414    Method* method() { return _method; }
 415 
 416    static void print_title(outputStream* st) {
 417      st->fill_to(col1);
 418      st->print("%11s", "Interpreted");
 419      ProfilerNode::print_title(st);
 420    }
 421 
 422    void print(outputStream* st, int total_ticks) {
 423      ProfilerNode::print(st, total_ticks);
 424    }
 425 
 426    void print_method_on(outputStream* st) {
 427      ProfilerNode::print_method_on(st);
 428      MethodCounters* mcs = method()->method_counters();
 429      if (Verbose && mcs != NULL) mcs->invocation_counter()->print_short();
 430    }
 431 };
 432 
 433 class compiledNode : public ProfilerNode {
 434  private:
 435    Method* _method;
 436    oop       _class_loader;  // needed to keep metadata for the method alive
 437  public:
 438    compiledNode(Method* method, TickPosition where) : ProfilerNode() {
 439      _method = method;
 440      _class_loader = method->method_holder()->class_loader();
 441      update(where);
 442   }
 443   bool is_compiled()    const { return true; }
 444 
 445   bool compiled_match(Method* m) const {
 446     return _method == m;
 447   }
 448 
 449   Method* method()         { return _method; }
 450 
 451   void oops_do(OopClosure* f) {
 452     f->do_oop(&_class_loader);
 453   }
 454 
 455   static void print_title(outputStream* st) {
 456     st->fill_to(col1);
 457     st->print("%11s", "Compiled");
 458     ProfilerNode::print_title(st);
 459   }
 460 
 461   void print(outputStream* st, int total_ticks) {
 462     ProfilerNode::print(st, total_ticks);
 463   }
 464 
 465   void print_method_on(outputStream* st) {
 466     ProfilerNode::print_method_on(st);
 467   }
 468 };
 469 
 470 class stubNode : public ProfilerNode {
 471  private:
 472   Method* _method;
 473   oop       _class_loader;  // needed to keep metadata for the method alive
 474   const char* _symbol;   // The name of the nearest VM symbol (for +ProfileVM). Points to a unique string
 475  public:
 476    stubNode(Method* method, const char* name, TickPosition where) : ProfilerNode() {
 477      _method = method;
 478      _class_loader = method->method_holder()->class_loader();
 479      _symbol = name;
 480      update(where);
 481    }
 482 
 483    bool is_stub() const { return true; }
 484 
 485    void oops_do(OopClosure* f) {
 486      f->do_oop(&_class_loader);
 487    }
 488 
 489    bool stub_match(Method* m, const char* name) const {
 490      return (_method == m) && (_symbol == name);
 491    }
 492 
 493    Method* method() { return _method; }
 494 
 495    static void print_title(outputStream* st) {
 496      st->fill_to(col1);
 497      st->print("%11s", "Stub");
 498      ProfilerNode::print_title(st);
 499    }
 500 
 501    void print(outputStream* st, int total_ticks) {
 502      ProfilerNode::print(st, total_ticks);
 503    }
 504 
 505    void print_method_on(outputStream* st) {
 506      ProfilerNode::print_method_on(st);
 507      print_symbol_on(st);
 508    }
 509 
 510   void print_symbol_on(outputStream* st) {
 511     if(_symbol) {
 512       st->print("  (%s)", _symbol);
 513     }
 514   }
 515 };
 516 
 517 class adapterNode : public ProfilerNode {
 518  public:
 519    adapterNode(TickPosition where) : ProfilerNode() {
 520      update(where);
 521   }
 522   bool is_compiled()    const { return true; }
 523 
 524   bool adapter_match() const { return true; }
 525 
 526   Method* method()         { return NULL; }
 527 
 528   void oops_do(OopClosure* f) {
 529     ;
 530   }
 531 
 532   void print(outputStream* st, int total_ticks) {
 533     ProfilerNode::print(st, total_ticks);
 534   }
 535 
 536   void print_method_on(outputStream* st) {
 537     st->print("%s", "adapters");
 538   }
 539 };
 540 
 541 class runtimeStubNode : public ProfilerNode {
 542  private:
 543    const CodeBlob* _stub;
 544   const char* _symbol;     // The name of the nearest VM symbol when ProfileVM is on. Points to a unique string.
 545  public:
 546    runtimeStubNode(const CodeBlob* stub, const char* name, TickPosition where) : ProfilerNode(), _stub(stub),  _symbol(name) {
 547      assert(stub->is_runtime_stub(), "wrong code blob");
 548      update(where);
 549    }
 550 
 551   bool is_runtime_stub() const { return true; }
 552 
 553   bool runtimeStub_match(const CodeBlob* stub, const char* name) const {
 554     assert(stub->is_runtime_stub(), "wrong code blob");
 555     return ((RuntimeStub*)_stub)->entry_point() == ((RuntimeStub*)stub)->entry_point() &&
 556             (_symbol == name);
 557   }
 558 
 559   Method* method() { return NULL; }
 560 
 561   static void print_title(outputStream* st) {
 562     st->fill_to(col1);
 563     st->print("%11s", "Runtime stub");
 564     ProfilerNode::print_title(st);
 565   }
 566 
 567   void oops_do(OopClosure* f) {
 568     ;
 569   }
 570 
 571   void print(outputStream* st, int total_ticks) {
 572     ProfilerNode::print(st, total_ticks);
 573   }
 574 
 575   void print_method_on(outputStream* st) {
 576     st->print("%s", ((RuntimeStub*)_stub)->name());
 577     print_symbol_on(st);
 578   }
 579 
 580   void print_symbol_on(outputStream* st) {
 581     if(_symbol) {
 582       st->print("  (%s)", _symbol);
 583     }
 584   }
 585 };
 586 
 587 
 588 class unknown_compiledNode : public ProfilerNode {
 589  const char *_name;
 590  public:
 591    unknown_compiledNode(const CodeBlob* cb, TickPosition where) : ProfilerNode() {
 592      if ( cb->is_buffer_blob() )
 593        _name = ((BufferBlob*)cb)->name();
 594      else
 595        _name = ((SingletonBlob*)cb)->name();
 596      update(where);
 597   }
 598   bool is_compiled()    const { return true; }
 599 
 600   bool unknown_compiled_match(const CodeBlob* cb) const {
 601      if ( cb->is_buffer_blob() )
 602        return !strcmp(((BufferBlob*)cb)->name(), _name);
 603      else
 604        return !strcmp(((SingletonBlob*)cb)->name(), _name);
 605   }
 606 
 607   Method* method()         { return NULL; }
 608 
 609   void oops_do(OopClosure* f) {
 610     ;
 611   }
 612 
 613   void print(outputStream* st, int total_ticks) {
 614     ProfilerNode::print(st, total_ticks);
 615   }
 616 
 617   void print_method_on(outputStream* st) {
 618     st->print("%s", _name);
 619   }
 620 };
 621 
 622 class vmNode : public ProfilerNode {
 623  private:
 624   const char* _name; // "optional" name obtained by os means such as dll lookup
 625  public:
 626   vmNode(const TickPosition where) : ProfilerNode() {
 627     _name = NULL;
 628     update(where);
 629   }
 630 
 631   vmNode(const char* name, const TickPosition where) : ProfilerNode() {
 632     _name = name;
 633     update(where);
 634   }
 635 
 636   const char *name()    const { return _name; }
 637   bool is_compiled()    const { return true; }
 638 
 639   bool vm_match(const char* name) const { return strcmp(name, _name) == 0; }
 640 
 641   Method* method()          { return NULL; }
 642 
 643   static int hash(const char* name){
 644     // Compute a simple hash
 645     const char* cp = name;
 646     int h = 0;
 647 
 648     if(name != NULL){
 649       while(*cp != '\0'){
 650         h = (h << 1) ^ *cp;
 651         cp++;
 652       }
 653     }
 654     return h;
 655   }
 656 
 657   void oops_do(OopClosure* f) {
 658     ;
 659   }
 660 
 661   void print(outputStream* st, int total_ticks) {
 662     ProfilerNode::print(st, total_ticks);
 663   }
 664 
 665   void print_method_on(outputStream* st) {
 666     if(_name==NULL){
 667       st->print("%s", "unknown code");
 668     }
 669     else {
 670       st->print("%s", _name);
 671     }
 672   }
 673 };
 674 
 675 void ThreadProfiler::interpreted_update(Method* method, TickPosition where) {
 676   int index = entry(ProfilerNode::hash(method));
 677   if (!table[index]) {
 678     table[index] = new (this) interpretedNode(method, where);
 679   } else {
 680     ProfilerNode* prev = table[index];
 681     for(ProfilerNode* node = prev; node; node = node->next()) {
 682       if (node->interpreted_match(method)) {
 683         node->update(where);
 684         return;
 685       }
 686       prev = node;
 687     }
 688     prev->set_next(new (this) interpretedNode(method, where));
 689   }
 690 }
 691 
 692 void ThreadProfiler::compiled_update(Method* method, TickPosition where) {
 693   int index = entry(ProfilerNode::hash(method));
 694   if (!table[index]) {
 695     table[index] = new (this) compiledNode(method, where);
 696   } else {
 697     ProfilerNode* prev = table[index];
 698     for(ProfilerNode* node = prev; node; node = node->next()) {
 699       if (node->compiled_match(method)) {
 700         node->update(where);
 701         return;
 702       }
 703       prev = node;
 704     }
 705     prev->set_next(new (this) compiledNode(method, where));
 706   }
 707 }
 708 
 709 void ThreadProfiler::stub_update(Method* method, const char* name, TickPosition where) {
 710   int index = entry(ProfilerNode::hash(method));
 711   if (!table[index]) {
 712     table[index] = new (this) stubNode(method, name, where);
 713   } else {
 714     ProfilerNode* prev = table[index];
 715     for(ProfilerNode* node = prev; node; node = node->next()) {
 716       if (node->stub_match(method, name)) {
 717         node->update(where);
 718         return;
 719       }
 720       prev = node;
 721     }
 722     prev->set_next(new (this) stubNode(method, name, where));
 723   }
 724 }
 725 
 726 void ThreadProfiler::adapter_update(TickPosition where) {
 727   int index = 0;
 728   if (!table[index]) {
 729     table[index] = new (this) adapterNode(where);
 730   } else {
 731     ProfilerNode* prev = table[index];
 732     for(ProfilerNode* node = prev; node; node = node->next()) {
 733       if (node->adapter_match()) {
 734         node->update(where);
 735         return;
 736       }
 737       prev = node;
 738     }
 739     prev->set_next(new (this) adapterNode(where));
 740   }
 741 }
 742 
 743 void ThreadProfiler::runtime_stub_update(const CodeBlob* stub, const char* name, TickPosition where) {
 744   int index = 0;
 745   if (!table[index]) {
 746     table[index] = new (this) runtimeStubNode(stub, name, where);
 747   } else {
 748     ProfilerNode* prev = table[index];
 749     for(ProfilerNode* node = prev; node; node = node->next()) {
 750       if (node->runtimeStub_match(stub, name)) {
 751         node->update(where);
 752         return;
 753       }
 754       prev = node;
 755     }
 756     prev->set_next(new (this) runtimeStubNode(stub, name, where));
 757   }
 758 }
 759 
 760 
 761 void ThreadProfiler::unknown_compiled_update(const CodeBlob* cb, TickPosition where) {
 762   int index = 0;
 763   if (!table[index]) {
 764     table[index] = new (this) unknown_compiledNode(cb, where);
 765   } else {
 766     ProfilerNode* prev = table[index];
 767     for(ProfilerNode* node = prev; node; node = node->next()) {
 768       if (node->unknown_compiled_match(cb)) {
 769         node->update(where);
 770         return;
 771       }
 772       prev = node;
 773     }
 774     prev->set_next(new (this) unknown_compiledNode(cb, where));
 775   }
 776 }
 777 
 778 void ThreadProfiler::vm_update(TickPosition where) {
 779   vm_update(NULL, where);
 780 }
 781 
 782 void ThreadProfiler::vm_update(const char* name, TickPosition where) {
 783   int index = entry(vmNode::hash(name));
 784   assert(index >= 0, "Must be positive");
 785   // Note that we call strdup below since the symbol may be resource allocated
 786   if (!table[index]) {
 787     table[index] = new (this) vmNode(os::strdup(name), where);
 788   } else {
 789     ProfilerNode* prev = table[index];
 790     for(ProfilerNode* node = prev; node; node = node->next()) {
 791       if (((vmNode *)node)->vm_match(name)) {
 792         node->update(where);
 793         return;
 794       }
 795       prev = node;
 796     }
 797     prev->set_next(new (this) vmNode(os::strdup(name), where));
 798   }
 799 }
 800 
 801 
 802 class FlatProfilerTask : public PeriodicTask {
 803 public:
 804   FlatProfilerTask(int interval_time) : PeriodicTask(interval_time) {}
 805   void task();
 806 };
 807 
 808 void FlatProfiler::record_vm_operation() {
 809   if (Universe::heap()->is_gc_active()) {
 810     FlatProfiler::received_gc_ticks += 1;
 811     return;
 812   }
 813 
 814   if (DeoptimizationMarker::is_active()) {
 815     FlatProfiler::deopt_ticks += 1;
 816     return;
 817   }
 818 
 819   FlatProfiler::vm_operation_ticks += 1;
 820 }
 821 
 822 void FlatProfiler::record_vm_tick() {
 823   // Profile the VM Thread itself if needed
 824   // This is done without getting the Threads_lock and we can go deep
 825   // inside Safepoint, etc.
 826   if( ProfileVM  ) {
 827     ResourceMark rm;
 828     ExtendedPC epc;
 829     const char *name = NULL;
 830     char buf[256];
 831     buf[0] = '\0';
 832 
 833     vm_thread_profiler->inc_thread_ticks();
 834 
 835     // Get a snapshot of a current VMThread pc (and leave it running!)
 836     // The call may fail if, for instance the VM thread is interrupted while
 837     // holding the Interrupt_lock or for other reasons.
 838     epc = os::get_thread_pc(VMThread::vm_thread());
 839     if(epc.pc() != NULL) {
 840       if (os::dll_address_to_function_name(epc.pc(), buf, sizeof(buf), NULL)) {
 841          name = buf;
 842       }
 843     }
 844     if (name != NULL) {
 845       vm_thread_profiler->vm_update(name, tp_native);
 846     }
 847   }
 848 }
 849 
 850 void FlatProfiler::record_thread_ticks() {
 851 
 852   int maxthreads, suspendedthreadcount;
 853   JavaThread** threadsList;
 854   bool interval_expired = false;
 855 
 856   if (ProfileIntervals &&
 857       (FlatProfiler::received_ticks >= interval_ticks_previous + ProfileIntervalsTicks)) {
 858     interval_expired = true;
 859     interval_ticks_previous = FlatProfiler::received_ticks;
 860   }
 861 
 862   // Try not to wait for the Threads_lock
 863   if (Threads_lock->try_lock()) {
 864     {  // Threads_lock scope
 865       maxthreads = Threads::number_of_threads();
 866       threadsList = NEW_C_HEAP_ARRAY(JavaThread *, maxthreads, mtInternal);
 867       suspendedthreadcount = 0;
 868       for (JavaThread* tp = Threads::first(); tp != NULL; tp = tp->next()) {
 869         if (tp->is_Compiler_thread()) {
 870           // Only record ticks for active compiler threads
 871           CompilerThread* cthread = (CompilerThread*)tp;
 872           if (cthread->task() != NULL) {
 873             // The compiler is active.  If we need to access any of the fields
 874             // of the compiler task we should suspend the CompilerThread first.
 875             FlatProfiler::compiler_ticks += 1;
 876             continue;
 877           }
 878         }
 879 
 880         // First externally suspend all threads by marking each for
 881         // external suspension - so it will stop at its next transition
 882         // Then do a safepoint
 883         ThreadProfiler* pp = tp->get_thread_profiler();
 884         if (pp != NULL && pp->engaged) {
 885           MutexLockerEx ml(tp->SR_lock(), Mutex::_no_safepoint_check_flag);
 886           if (!tp->is_external_suspend() && !tp->is_exiting()) {
 887             tp->set_external_suspend();
 888             threadsList[suspendedthreadcount++] = tp;
 889           }
 890         }
 891       }
 892       Threads_lock->unlock();
 893     }
 894     // Suspend each thread. This call should just return
 895     // for any threads that have already self-suspended
 896     // Net result should be one safepoint
 897     for (int j = 0; j < suspendedthreadcount; j++) {
 898       JavaThread *tp = threadsList[j];
 899       if (tp) {
 900         tp->java_suspend();
 901       }
 902     }
 903 
 904     // We are responsible for resuming any thread on this list
 905     for (int i = 0; i < suspendedthreadcount; i++) {
 906       JavaThread *tp = threadsList[i];
 907       if (tp) {
 908         ThreadProfiler* pp = tp->get_thread_profiler();
 909         if (pp != NULL && pp->engaged) {
 910           HandleMark hm;
 911           FlatProfiler::delivered_ticks += 1;
 912           if (interval_expired) {
 913           FlatProfiler::interval_record_thread(pp);
 914           }
 915           // This is the place where we check to see if a user thread is
 916           // blocked waiting for compilation.
 917           if (tp->blocked_on_compilation()) {
 918             pp->compiler_ticks += 1;
 919             pp->interval_data_ref()->inc_compiling();
 920           } else {
 921             pp->record_tick(tp);
 922           }
 923         }
 924         MutexLocker ml(Threads_lock);
 925         tp->java_resume();
 926       }
 927     }
 928     if (interval_expired) {
 929       FlatProfiler::interval_print();
 930       FlatProfiler::interval_reset();
 931     }
 932 
 933     FREE_C_HEAP_ARRAY(JavaThread *, threadsList, mtInternal);
 934   } else {
 935     // Couldn't get the threads lock, just record that rather than blocking
 936     FlatProfiler::threads_lock_ticks += 1;
 937   }
 938 
 939 }
 940 
 941 void FlatProfilerTask::task() {
 942   FlatProfiler::received_ticks += 1;
 943 
 944   if (ProfileVM) {
 945     FlatProfiler::record_vm_tick();
 946   }
 947 
 948   VM_Operation* op = VMThread::vm_operation();
 949   if (op != NULL) {
 950     FlatProfiler::record_vm_operation();
 951     if (SafepointSynchronize::is_at_safepoint()) {
 952       return;
 953     }
 954   }
 955   FlatProfiler::record_thread_ticks();
 956 }
 957 
 958 void ThreadProfiler::record_interpreted_tick(JavaThread* thread, frame fr, TickPosition where, int* ticks) {
 959   FlatProfiler::all_int_ticks++;
 960   if (!FlatProfiler::full_profile()) {
 961     return;
 962   }
 963 
 964   if (!fr.is_interpreted_frame_valid(thread)) {
 965     // tick came at a bad time
 966     interpreter_ticks += 1;
 967     FlatProfiler::interpreter_ticks += 1;
 968     return;
 969   }
 970 
 971   // The frame has been fully validated so we can trust the method and bci
 972 
 973   Method* method = *fr.interpreter_frame_method_addr();
 974 
 975   interpreted_update(method, where);
 976 
 977   // update byte code table
 978   InterpreterCodelet* desc = Interpreter::codelet_containing(fr.pc());
 979   if (desc != NULL && desc->bytecode() >= 0) {
 980     ticks[desc->bytecode()]++;
 981   }
 982 }
 983 
 984 void ThreadProfiler::record_compiled_tick(JavaThread* thread, frame fr, TickPosition where) {
 985   const char *name = NULL;
 986   TickPosition localwhere = where;
 987 
 988   FlatProfiler::all_comp_ticks++;
 989   if (!FlatProfiler::full_profile()) return;
 990 
 991   CodeBlob* cb = fr.cb();
 992 
 993 // For runtime stubs, record as native rather than as compiled
 994    if (cb->is_runtime_stub()) {
 995         RegisterMap map(thread, false);
 996         fr = fr.sender(&map);
 997         cb = fr.cb();
 998         localwhere = tp_native;
 999   }
1000   Method* method = (cb->is_nmethod()) ? ((nmethod *)cb)->method() :
1001                                           (Method*)NULL;
1002 
1003   if (method == NULL) {
1004     if (cb->is_runtime_stub())
1005       runtime_stub_update(cb, name, localwhere);
1006     else
1007       unknown_compiled_update(cb, localwhere);
1008   }
1009   else {
1010     if (method->is_native()) {
1011       stub_update(method, name, localwhere);
1012     } else {
1013       compiled_update(method, localwhere);
1014     }
1015   }
1016 }
1017 
1018 extern "C" void find(int x);
1019 
1020 
1021 void ThreadProfiler::record_tick_for_running_frame(JavaThread* thread, frame fr) {
1022   // The tick happened in real code -> non VM code
1023   if (fr.is_interpreted_frame()) {
1024     interval_data_ref()->inc_interpreted();
1025     record_interpreted_tick(thread, fr, tp_code, FlatProfiler::bytecode_ticks);
1026     return;
1027   }
1028 
1029   if (CodeCache::contains(fr.pc())) {
1030     interval_data_ref()->inc_compiled();
1031     PCRecorder::record(fr.pc());
1032     record_compiled_tick(thread, fr, tp_code);
1033     return;
1034   }
1035 
1036   if (VtableStubs::stub_containing(fr.pc()) != NULL) {
1037     unknown_ticks_array[ut_vtable_stubs] += 1;
1038     return;
1039   }
1040 
1041   frame caller = fr.profile_find_Java_sender_frame(thread);
1042 
1043   if (caller.sp() != NULL && caller.pc() != NULL) {
1044     record_tick_for_calling_frame(thread, caller);
1045     return;
1046   }
1047 
1048   unknown_ticks_array[ut_running_frame] += 1;
1049   FlatProfiler::unknown_ticks += 1;
1050 }
1051 
1052 void ThreadProfiler::record_tick_for_calling_frame(JavaThread* thread, frame fr) {
1053   // The tick happened in VM code
1054   interval_data_ref()->inc_native();
1055   if (fr.is_interpreted_frame()) {
1056     record_interpreted_tick(thread, fr, tp_native, FlatProfiler::bytecode_ticks_stub);
1057     return;
1058   }
1059   if (CodeCache::contains(fr.pc())) {
1060     record_compiled_tick(thread, fr, tp_native);
1061     return;
1062   }
1063 
1064   frame caller = fr.profile_find_Java_sender_frame(thread);
1065 
1066   if (caller.sp() != NULL && caller.pc() != NULL) {
1067     record_tick_for_calling_frame(thread, caller);
1068     return;
1069   }
1070 
1071   unknown_ticks_array[ut_calling_frame] += 1;
1072   FlatProfiler::unknown_ticks += 1;
1073 }
1074 
1075 void ThreadProfiler::record_tick(JavaThread* thread) {
1076   FlatProfiler::all_ticks++;
1077   thread_ticks += 1;
1078 
1079   // Here's another way to track global state changes.
1080   // When the class loader starts it marks the ThreadProfiler to tell it it is in the class loader
1081   // and we check that here.
1082   // This is more direct, and more than one thread can be in the class loader at a time,
1083   // but it does mean the class loader has to know about the profiler.
1084   if (region_flag[ThreadProfilerMark::classLoaderRegion]) {
1085     class_loader_ticks += 1;
1086     FlatProfiler::class_loader_ticks += 1;
1087     return;
1088   } else if (region_flag[ThreadProfilerMark::extraRegion]) {
1089     extra_ticks += 1;
1090     FlatProfiler::extra_ticks += 1;
1091     return;
1092   }
1093   // Note that the WatcherThread can now stop for safepoints
1094   uint32_t debug_bits = 0;
1095   if (!thread->wait_for_ext_suspend_completion(SuspendRetryCount,
1096       SuspendRetryDelay, &debug_bits)) {
1097     unknown_ticks_array[ut_unknown_thread_state] += 1;
1098     FlatProfiler::unknown_ticks += 1;
1099     return;
1100   }
1101 
1102   frame fr;
1103 
1104   switch (thread->thread_state()) {
1105   case _thread_in_native:
1106   case _thread_in_native_trans:
1107   case _thread_in_vm:
1108   case _thread_in_vm_trans:
1109     if (thread->profile_last_Java_frame(&fr)) {
1110       if (fr.is_runtime_frame()) {
1111         RegisterMap map(thread, false);
1112         fr = fr.sender(&map);
1113       }
1114       record_tick_for_calling_frame(thread, fr);
1115     } else {
1116       unknown_ticks_array[ut_no_last_Java_frame] += 1;
1117       FlatProfiler::unknown_ticks += 1;
1118     }
1119     break;
1120   // handle_special_runtime_exit_condition self-suspends threads in Java
1121   case _thread_in_Java:
1122   case _thread_in_Java_trans:
1123     if (thread->profile_last_Java_frame(&fr)) {
1124       if (fr.is_safepoint_blob_frame()) {
1125         RegisterMap map(thread, false);
1126         fr = fr.sender(&map);
1127       }
1128       record_tick_for_running_frame(thread, fr);
1129     } else {
1130       unknown_ticks_array[ut_no_last_Java_frame] += 1;
1131       FlatProfiler::unknown_ticks += 1;
1132     }
1133     break;
1134   case _thread_blocked:
1135   case _thread_blocked_trans:
1136     if (thread->osthread() && thread->osthread()->get_state() == RUNNABLE) {
1137         if (thread->profile_last_Java_frame(&fr)) {
1138           if (fr.is_safepoint_blob_frame()) {
1139             RegisterMap map(thread, false);
1140             fr = fr.sender(&map);
1141             record_tick_for_running_frame(thread, fr);
1142           } else {
1143             record_tick_for_calling_frame(thread, fr);
1144           }
1145         } else {
1146           unknown_ticks_array[ut_no_last_Java_frame] += 1;
1147           FlatProfiler::unknown_ticks += 1;
1148         }
1149     } else {
1150           blocked_ticks += 1;
1151           FlatProfiler::blocked_ticks += 1;
1152     }
1153     break;
1154   case _thread_uninitialized:
1155   case _thread_new:
1156   // not used, included for completeness
1157   case _thread_new_trans:
1158      unknown_ticks_array[ut_no_last_Java_frame] += 1;
1159      FlatProfiler::unknown_ticks += 1;
1160      break;
1161   default:
1162     unknown_ticks_array[ut_unknown_thread_state] += 1;
1163     FlatProfiler::unknown_ticks += 1;
1164     break;
1165   }
1166   return;
1167 }
1168 
1169 void ThreadProfiler::engage() {
1170   engaged = true;
1171   timer.start();
1172 }
1173 
1174 void ThreadProfiler::disengage() {
1175   engaged = false;
1176   timer.stop();
1177 }
1178 
1179 void ThreadProfiler::initialize() {
1180   for (int index = 0; index < table_size; index++) {
1181     table[index] = NULL;
1182   }
1183   thread_ticks = 0;
1184   blocked_ticks = 0;
1185   compiler_ticks = 0;
1186   interpreter_ticks = 0;
1187   for (int ut = 0; ut < ut_end; ut += 1) {
1188     unknown_ticks_array[ut] = 0;
1189   }
1190   region_flag[ThreadProfilerMark::classLoaderRegion] = false;
1191   class_loader_ticks = 0;
1192   region_flag[ThreadProfilerMark::extraRegion] = false;
1193   extra_ticks = 0;
1194   timer.start();
1195   interval_data_ref()->reset();
1196 }
1197 
1198 void ThreadProfiler::reset() {
1199   timer.stop();
1200   if (table != NULL) {
1201     for (int index = 0; index < table_size; index++) {
1202       ProfilerNode* n = table[index];
1203       if (n != NULL) {
1204         delete n;
1205       }
1206     }
1207   }
1208   initialize();
1209 }
1210 
1211 void FlatProfiler::allocate_table() {
1212   { // Bytecode table
1213     bytecode_ticks      = NEW_C_HEAP_ARRAY(int, Bytecodes::number_of_codes, mtInternal);
1214     bytecode_ticks_stub = NEW_C_HEAP_ARRAY(int, Bytecodes::number_of_codes, mtInternal);
1215     for(int index = 0; index < Bytecodes::number_of_codes; index++) {
1216       bytecode_ticks[index]      = 0;
1217       bytecode_ticks_stub[index] = 0;
1218     }
1219   }
1220 
1221   if (ProfilerRecordPC) PCRecorder::init();
1222 
1223   interval_data         = NEW_C_HEAP_ARRAY(IntervalData, interval_print_size, mtInternal);
1224   FlatProfiler::interval_reset();
1225 }
1226 
1227 void FlatProfiler::engage(JavaThread* mainThread, bool fullProfile) {
1228   full_profile_flag = fullProfile;
1229   if (bytecode_ticks == NULL) {
1230     allocate_table();
1231   }
1232   if(ProfileVM && (vm_thread_profiler == NULL)){
1233     vm_thread_profiler = new ThreadProfiler();
1234   }
1235   if (task == NULL) {
1236     task = new FlatProfilerTask(WatcherThread::delay_interval);
1237     task->enroll();
1238   }
1239   timer.start();
1240   if (mainThread != NULL) {
1241     // When mainThread was created, it might not have a ThreadProfiler
1242     ThreadProfiler* pp = mainThread->get_thread_profiler();
1243     if (pp == NULL) {
1244       mainThread->set_thread_profiler(new ThreadProfiler());
1245     } else {
1246       pp->reset();
1247     }
1248     mainThread->get_thread_profiler()->engage();
1249   }
1250   // This is where we would assign thread_profiler
1251   // if we wanted only one thread_profiler for all threads.
1252   thread_profiler = NULL;
1253 }
1254 
1255 void FlatProfiler::disengage() {
1256   if (!task) {
1257     return;
1258   }
1259   timer.stop();
1260   task->disenroll();
1261   delete task;
1262   task = NULL;
1263   if (thread_profiler != NULL) {
1264     thread_profiler->disengage();
1265   } else {
1266     MutexLocker tl(Threads_lock);
1267     for (JavaThread* tp = Threads::first(); tp != NULL; tp = tp->next()) {
1268       ThreadProfiler* pp = tp->get_thread_profiler();
1269       if (pp != NULL) {
1270         pp->disengage();
1271       }
1272     }
1273   }
1274 }
1275 
1276 void FlatProfiler::reset() {
1277   if (task) {
1278     disengage();
1279   }
1280 
1281   class_loader_ticks = 0;
1282   extra_ticks        = 0;
1283   received_gc_ticks  = 0;
1284   vm_operation_ticks = 0;
1285   compiler_ticks     = 0;
1286   deopt_ticks        = 0;
1287   interpreter_ticks  = 0;
1288   blocked_ticks      = 0;
1289   unknown_ticks      = 0;
1290   received_ticks     = 0;
1291   delivered_ticks    = 0;
1292   timer.stop();
1293 }
1294 
1295 bool FlatProfiler::is_active() {
1296   return task != NULL;
1297 }
1298 
1299 void FlatProfiler::print_byte_code_statistics() {
1300   GrowableArray <ProfilerNode*>* array = new GrowableArray<ProfilerNode*>(200);
1301 
1302   tty->print_cr(" Bytecode ticks:");
1303   for (int index = 0; index < Bytecodes::number_of_codes; index++) {
1304     if (FlatProfiler::bytecode_ticks[index] > 0 || FlatProfiler::bytecode_ticks_stub[index] > 0) {
1305       tty->print_cr("  %4d %4d = %s",
1306         FlatProfiler::bytecode_ticks[index],
1307         FlatProfiler::bytecode_ticks_stub[index],
1308         Bytecodes::name( (Bytecodes::Code) index));
1309     }
1310   }
1311   tty->cr();
1312 }
1313 
1314 void print_ticks(const char* title, int ticks, int total) {
1315   if (ticks > 0) {
1316     tty->print("%5.1f%% %5d", ticks * 100.0 / total, ticks);
1317     tty->fill_to(col3);
1318     tty->print("%s", title);
1319     tty->cr();
1320   }
1321 }
1322 
1323 void ThreadProfiler::print(const char* thread_name) {
1324   ResourceMark rm;
1325   MutexLocker ppl(ProfilePrint_lock);
1326   int index = 0; // Declared outside for loops for portability
1327 
1328   if (table == NULL) {
1329     return;
1330   }
1331 
1332   if (thread_ticks <= 0) {
1333     return;
1334   }
1335 
1336   const char* title = "too soon to tell";
1337   double secs = timer.seconds();
1338 
1339   GrowableArray <ProfilerNode*>* array = new GrowableArray<ProfilerNode*>(200);
1340   for(index = 0; index < table_size; index++) {
1341     for(ProfilerNode* node = table[index]; node; node = node->next())
1342       array->append(node);
1343   }
1344 
1345   array->sort(&ProfilerNode::compare);
1346 
1347   // compute total (sanity check)
1348   int active =
1349     class_loader_ticks +
1350     compiler_ticks +
1351     interpreter_ticks +
1352     unknown_ticks();
1353   for (index = 0; index < array->length(); index++) {
1354     active += array->at(index)->ticks.total();
1355   }
1356   int total = active + blocked_ticks;
1357 
1358   tty->cr();
1359   tty->print_cr("Flat profile of %3.2f secs (%d total ticks): %s", secs, total, thread_name);
1360   if (total != thread_ticks) {
1361     print_ticks("Lost ticks", thread_ticks-total, thread_ticks);
1362   }
1363   tty->cr();
1364 
1365   // print interpreted methods
1366   tick_counter interpreted_ticks;
1367   bool has_interpreted_ticks = false;
1368   int print_count = 0;
1369   for (index = 0; index < array->length(); index++) {
1370     ProfilerNode* n = array->at(index);
1371     if (n->is_interpreted()) {
1372       interpreted_ticks.add(&n->ticks);
1373       if (!has_interpreted_ticks) {
1374         interpretedNode::print_title(tty);
1375         has_interpreted_ticks = true;
1376       }
1377       if (print_count++ < ProfilerNumberOfInterpretedMethods) {
1378         n->print(tty, active);
1379       }
1380     }
1381   }
1382   if (has_interpreted_ticks) {
1383     if (print_count <= ProfilerNumberOfInterpretedMethods) {
1384       title = "Total interpreted";
1385     } else {
1386       title = "Total interpreted (including elided)";
1387     }
1388     interpretedNode::print_total(tty, &interpreted_ticks, active, title);
1389     tty->cr();
1390   }
1391 
1392   // print compiled methods
1393   tick_counter compiled_ticks;
1394   bool has_compiled_ticks = false;
1395   print_count = 0;
1396   for (index = 0; index < array->length(); index++) {
1397     ProfilerNode* n = array->at(index);
1398     if (n->is_compiled()) {
1399       compiled_ticks.add(&n->ticks);
1400       if (!has_compiled_ticks) {
1401         compiledNode::print_title(tty);
1402         has_compiled_ticks = true;
1403       }
1404       if (print_count++ < ProfilerNumberOfCompiledMethods) {
1405         n->print(tty, active);
1406       }
1407     }
1408   }
1409   if (has_compiled_ticks) {
1410     if (print_count <= ProfilerNumberOfCompiledMethods) {
1411       title = "Total compiled";
1412     } else {
1413       title = "Total compiled (including elided)";
1414     }
1415     compiledNode::print_total(tty, &compiled_ticks, active, title);
1416     tty->cr();
1417   }
1418 
1419   // print stub methods
1420   tick_counter stub_ticks;
1421   bool has_stub_ticks = false;
1422   print_count = 0;
1423   for (index = 0; index < array->length(); index++) {
1424     ProfilerNode* n = array->at(index);
1425     if (n->is_stub()) {
1426       stub_ticks.add(&n->ticks);
1427       if (!has_stub_ticks) {
1428         stubNode::print_title(tty);
1429         has_stub_ticks = true;
1430       }
1431       if (print_count++ < ProfilerNumberOfStubMethods) {
1432         n->print(tty, active);
1433       }
1434     }
1435   }
1436   if (has_stub_ticks) {
1437     if (print_count <= ProfilerNumberOfStubMethods) {
1438       title = "Total stub";
1439     } else {
1440       title = "Total stub (including elided)";
1441     }
1442     stubNode::print_total(tty, &stub_ticks, active, title);
1443     tty->cr();
1444   }
1445 
1446   // print runtime stubs
1447   tick_counter runtime_stub_ticks;
1448   bool has_runtime_stub_ticks = false;
1449   print_count = 0;
1450   for (index = 0; index < array->length(); index++) {
1451     ProfilerNode* n = array->at(index);
1452     if (n->is_runtime_stub()) {
1453       runtime_stub_ticks.add(&n->ticks);
1454       if (!has_runtime_stub_ticks) {
1455         runtimeStubNode::print_title(tty);
1456         has_runtime_stub_ticks = true;
1457       }
1458       if (print_count++ < ProfilerNumberOfRuntimeStubNodes) {
1459         n->print(tty, active);
1460       }
1461     }
1462   }
1463   if (has_runtime_stub_ticks) {
1464     if (print_count <= ProfilerNumberOfRuntimeStubNodes) {
1465       title = "Total runtime stubs";
1466     } else {
1467       title = "Total runtime stubs (including elided)";
1468     }
1469     runtimeStubNode::print_total(tty, &runtime_stub_ticks, active, title);
1470     tty->cr();
1471   }
1472 
1473   if (blocked_ticks + class_loader_ticks + interpreter_ticks + compiler_ticks + unknown_ticks() != 0) {
1474     tty->fill_to(col1);
1475     tty->print_cr("Thread-local ticks:");
1476     print_ticks("Blocked (of total)",  blocked_ticks,      total);
1477     print_ticks("Class loader",        class_loader_ticks, active);
1478     print_ticks("Extra",               extra_ticks,        active);
1479     print_ticks("Interpreter",         interpreter_ticks,  active);
1480     print_ticks("Compilation",         compiler_ticks,     active);
1481     print_ticks("Unknown: vtable stubs",  unknown_ticks_array[ut_vtable_stubs],         active);
1482     print_ticks("Unknown: null method",   unknown_ticks_array[ut_null_method],          active);
1483     print_ticks("Unknown: running frame", unknown_ticks_array[ut_running_frame],        active);
1484     print_ticks("Unknown: calling frame", unknown_ticks_array[ut_calling_frame],        active);
1485     print_ticks("Unknown: no pc",         unknown_ticks_array[ut_no_pc],                active);
1486     print_ticks("Unknown: no last frame", unknown_ticks_array[ut_no_last_Java_frame],   active);
1487     print_ticks("Unknown: thread_state",  unknown_ticks_array[ut_unknown_thread_state], active);
1488     tty->cr();
1489   }
1490 
1491   if (WizardMode) {
1492     tty->print_cr("Node area used: %dKb", (area_top - area_bottom) / 1024);
1493   }
1494   reset();
1495 }
1496 
1497 /*
1498 ThreadProfiler::print_unknown(){
1499   if (table == NULL) {
1500     return;
1501   }
1502 
1503   if (thread_ticks <= 0) {
1504     return;
1505   }
1506 } */
1507 
1508 void FlatProfiler::print(int unused) {
1509   ResourceMark rm;
1510   if (thread_profiler != NULL) {
1511     thread_profiler->print("All threads");
1512   } else {
1513     MutexLocker tl(Threads_lock);
1514     for (JavaThread* tp = Threads::first(); tp != NULL; tp = tp->next()) {
1515       ThreadProfiler* pp = tp->get_thread_profiler();
1516       if (pp != NULL) {
1517         pp->print(tp->get_thread_name());
1518       }
1519     }
1520   }
1521 
1522   if (ProfilerPrintByteCodeStatistics) {
1523     print_byte_code_statistics();
1524   }
1525 
1526   if (non_method_ticks() > 0) {
1527     tty->cr();
1528     tty->print_cr("Global summary of %3.2f seconds:", timer.seconds());
1529     print_ticks("Received ticks",      received_ticks,     received_ticks);
1530     print_ticks("Received GC ticks",   received_gc_ticks,  received_ticks);
1531     print_ticks("Compilation",         compiler_ticks,     received_ticks);
1532     print_ticks("Deoptimization",      deopt_ticks,        received_ticks);
1533     print_ticks("Other VM operations", vm_operation_ticks, received_ticks);
1534 #ifndef PRODUCT
1535     print_ticks("Blocked ticks",       blocked_ticks,      received_ticks);
1536     print_ticks("Threads_lock blocks", threads_lock_ticks, received_ticks);
1537     print_ticks("Delivered ticks",     delivered_ticks,    received_ticks);
1538     print_ticks("All ticks",           all_ticks,          received_ticks);
1539 #endif
1540     print_ticks("Class loader",        class_loader_ticks, received_ticks);
1541     print_ticks("Extra       ",        extra_ticks,        received_ticks);
1542     print_ticks("Interpreter",         interpreter_ticks,  received_ticks);
1543     print_ticks("Unknown code",        unknown_ticks,      received_ticks);
1544   }
1545 
1546   PCRecorder::print();
1547 
1548   if(ProfileVM){
1549     tty->cr();
1550     vm_thread_profiler->print("VM Thread");
1551   }
1552 }
1553 
1554 void IntervalData::print_header(outputStream* st) {
1555   st->print("i/c/n/g");
1556 }
1557 
1558 void IntervalData::print_data(outputStream* st) {
1559   st->print("%d/%d/%d/%d", interpreted(), compiled(), native(), compiling());
1560 }
1561 
1562 void FlatProfiler::interval_record_thread(ThreadProfiler* tp) {
1563   IntervalData id = tp->interval_data();
1564   int total = id.total();
1565   tp->interval_data_ref()->reset();
1566 
1567   // Insertion sort the data, if it's relevant.
1568   for (int i = 0; i < interval_print_size; i += 1) {
1569     if (total > interval_data[i].total()) {
1570       for (int j = interval_print_size - 1; j > i; j -= 1) {
1571         interval_data[j] = interval_data[j-1];
1572       }
1573       interval_data[i] = id;
1574       break;
1575     }
1576   }
1577 }
1578 
1579 void FlatProfiler::interval_print() {
1580   if ((interval_data[0].total() > 0)) {
1581     tty->stamp();
1582     tty->print("\t");
1583     IntervalData::print_header(tty);
1584     for (int i = 0; i < interval_print_size; i += 1) {
1585       if (interval_data[i].total() > 0) {
1586         tty->print("\t");
1587         interval_data[i].print_data(tty);
1588       }
1589     }
1590     tty->cr();
1591   }
1592 }
1593 
1594 void FlatProfiler::interval_reset() {
1595   for (int i = 0; i < interval_print_size; i += 1) {
1596     interval_data[i].reset();
1597   }
1598 }
1599 
1600 void ThreadProfiler::oops_do(OopClosure* f) {
1601   if (table == NULL) return;
1602 
1603   for(int index = 0; index < table_size; index++) {
1604     for(ProfilerNode* node = table[index]; node; node = node->next())
1605       node->oops_do(f);
1606   }
1607 }
1608 
1609 void FlatProfiler::oops_do(OopClosure* f) {
1610   if (thread_profiler != NULL) {
1611     thread_profiler->oops_do(f);
1612   } else {
1613     for (JavaThread* tp = Threads::first(); tp != NULL; tp = tp->next()) {
1614       ThreadProfiler* pp = tp->get_thread_profiler();
1615       if (pp != NULL) {
1616         pp->oops_do(f);
1617       }
1618     }
1619   }
1620 }