1 /*
   2  * Copyright (c) 1998, 2019, 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 "code/codeBlob.hpp"
  27 #include "code/codeCache.hpp"
  28 #include "code/nmethod.hpp"
  29 #include "code/scopeDesc.hpp"
  30 #include "compiler/oopMap.hpp"
  31 #include "compiler/oopMap.inline.hpp"
  32 #include "compiler/oopMapStubGenerator.hpp"
  33 #include "gc/shared/collectedHeap.hpp"
  34 #include "logging/log.hpp"
  35 #include "logging/logStream.hpp"
  36 #include "memory/allocation.inline.hpp"
  37 #include "memory/iterator.hpp"
  38 #include "memory/resourceArea.hpp"
  39 #include "oops/compressedOops.hpp"
  40 #include "runtime/atomic.hpp"
  41 #include "runtime/frame.inline.hpp"
  42 #include "runtime/handles.inline.hpp"
  43 #include "runtime/signature.hpp"
  44 #include "utilities/align.hpp"
  45 #include "utilities/lockFreeStack.hpp"
  46 #ifdef COMPILER1
  47 #include "c1/c1_Defs.hpp"
  48 #endif
  49 #ifdef COMPILER2
  50 #include "opto/optoreg.hpp"
  51 #endif
  52 
  53 // OopMapStream
  54 
  55 OopMapStream::OopMapStream(const OopMap* oop_map, int oop_types_mask)
  56   : _stream(oop_map->write_stream()->buffer()) {
  57   // _stream = new CompressedReadStream();
  58   _mask = oop_types_mask;
  59   _size = oop_map->omv_count();
  60   _position = 0;
  61   _valid_omv = false;
  62 }
  63 
  64 OopMapStream::OopMapStream(const ImmutableOopMap* oop_map, int oop_types_mask)
  65   : _stream(oop_map->data_addr()) {
  66   // _stream = new CompressedReadStream(oop_map->data_addr());
  67   _mask = oop_types_mask;
  68   _size = oop_map->count();
  69   _position = 0;
  70   _valid_omv = false;
  71 }
  72 
  73 void OopMapStream::find_next() {
  74   while(_position++ < _size) {
  75     _omv.read_from(&_stream);
  76     if(((int)_omv.type() & _mask) > 0) {
  77       _valid_omv = true;
  78       return;
  79     }
  80   }
  81   _valid_omv = false;
  82 }
  83 
  84 
  85 // OopMap
  86 
  87 // frame_size units are stack-slots (4 bytes) NOT intptr_t; we can name odd
  88 // slots to hold 4-byte values like ints and floats in the LP64 build.
  89 OopMap::OopMap(int frame_size, int arg_count) {
  90   // OopMaps are usually quite so small, so pick a small initial size
  91   set_write_stream(new CompressedWriteStream(32));
  92   set_omv_count(0);
  93   _num_oops = 0;
  94   _index = -1;
  95 
  96 #ifdef ASSERT
  97   _locs_length = VMRegImpl::stack2reg(0)->value() + frame_size + arg_count;
  98   _locs_used   = NEW_RESOURCE_ARRAY(OopMapValue::oop_types, _locs_length);
  99   for(int i = 0; i < _locs_length; i++) _locs_used[i] = OopMapValue::unused_value;
 100 #endif
 101 }
 102 
 103 
 104 OopMap::OopMap(OopMap::DeepCopyToken, OopMap* source) {
 105   // This constructor does a deep copy
 106   // of the source OopMap.
 107   set_write_stream(new CompressedWriteStream(source->omv_count() * 2));
 108   set_omv_count(0);
 109   set_offset(source->offset());
 110   _num_oops = source->num_oops();
 111   _index = -1;
 112 
 113 #ifdef ASSERT
 114   _locs_length = source->_locs_length;
 115   _locs_used = NEW_RESOURCE_ARRAY(OopMapValue::oop_types, _locs_length);
 116   for(int i = 0; i < _locs_length; i++) _locs_used[i] = OopMapValue::unused_value;
 117 #endif
 118 
 119   // We need to copy the entries too.
 120   for (OopMapStream oms(source); !oms.is_done(); oms.next()) {
 121     OopMapValue omv = oms.current();
 122     omv.write_on(write_stream());
 123     increment_count();
 124   }
 125 }
 126 
 127 
 128 OopMap* OopMap::deep_copy() {
 129   return new OopMap(_deep_copy_token, this);
 130 }
 131 
 132 void OopMap::copy_data_to(address addr) const {
 133   memcpy(addr, write_stream()->buffer(), write_stream()->position());
 134 }
 135 
 136 class OopMapSort {
 137 private:
 138   const OopMap* _map;
 139   OopMapValue* _values;
 140   int _count;
 141 
 142 public:
 143   OopMapSort(const OopMap* map) : _map(map), _count(0) {
 144     _values = NEW_RESOURCE_ARRAY(OopMapValue, _map->omv_count());
 145   }
 146 
 147   void sort();
 148 
 149   void print();
 150 
 151   void write(CompressedWriteStream* stream) {
 152     for (int i = 0; i < _count; ++i) {
 153       _values[i].write_on(stream);
 154     }
 155   }
 156 
 157 private:
 158   int find_derived_position(OopMapValue omv, int start) {
 159     assert(omv.type() == OopMapValue::derived_oop_value, "");
 160 
 161     VMReg base = omv.content_reg();
 162     int i = start;
 163 
 164     for (; i < _count; ++i) {
 165       if (base == _values[i].reg()) {
 166 
 167         for (int n = i + 1; n < _count; ++n) {
 168           if (_values[i].type() != OopMapValue::derived_oop_value || _values[i].content_reg() != base) {
 169             return n;
 170           }
 171 
 172           if (derived_cost(_values[i]) > derived_cost(omv)) {
 173             return n;
 174           }
 175         }
 176         return _count;
 177       }
 178     }
 179 
 180     assert(false, "failed to find base");
 181     return -1;
 182   }
 183 
 184   int find_position(OopMapValue omv, int start) {
 185     assert(omv.type() != OopMapValue::derived_oop_value, "");
 186 
 187     int i = start;
 188     for (; i < _count; ++i) {
 189       if (omv_cost(_values[i]) > omv_cost(omv)) {
 190         return i;
 191       }
 192     }
 193     assert(i < _map->omv_count(), "bounds check");
 194     return i;
 195   }
 196 
 197   void insert(OopMapValue value, int pos) {
 198     assert(pos >= 0 && pos < _map->omv_count(), "bounds check");
 199     assert(pos <= _count, "sanity");
 200 
 201     if (pos < _count) {
 202       OopMapValue prev = _values[pos];
 203 
 204       for (int i = pos; i < _count; ++i) {
 205         OopMapValue tmp = _values[i+1];
 206         _values[i+1] = prev;
 207         prev = tmp;
 208       }
 209     }
 210     _values[pos] = value;
 211 
 212     ++_count;
 213   }
 214 
 215   int omv_cost(OopMapValue omv) {
 216     assert(omv.type() == OopMapValue::oop_value || omv.type() == OopMapValue::narrowoop_value, "");
 217     return reg_cost(omv.reg());
 218   }
 219 
 220   int reg_cost(VMReg reg) {
 221     if (reg->is_reg()) {
 222       return 0;
 223     }
 224     return reg->reg2stack() * VMRegImpl::stack_slot_size;
 225   }
 226 
 227   int derived_cost(OopMapValue omv) {
 228     return reg_cost(omv.reg());
 229   }
 230 };
 231 
 232 void OopMapSort::sort() {
 233   for (OopMapStream oms(_map); !oms.is_done(); oms.next()) {
 234     OopMapValue omv = oms.current();
 235     assert(omv.type() == OopMapValue::oop_value || omv.type() == OopMapValue::narrowoop_value || omv.type() == OopMapValue::derived_oop_value || omv.type() == OopMapValue::callee_saved_value, "");
 236   }
 237 
 238   for (OopMapStream oms(_map, OopMapValue::callee_saved_value); !oms.is_done(); oms.next()) {
 239     insert(oms.current(), _count);
 240   }
 241 
 242   int start = _count;
 243   for (OopMapStream oms(_map, OopMapValue::oop_value | OopMapValue::narrowoop_value); !oms.is_done(); oms.next()) {
 244     OopMapValue omv = oms.current();
 245     int pos = find_position(omv, start);
 246     insert(omv, pos);
 247   }
 248 
 249   for (OopMapStream oms(_map, OopMapValue::derived_oop_value); !oms.is_done(); oms.next()) {
 250     OopMapValue omv = oms.current();
 251     int pos = find_derived_position(omv, start);
 252     assert(pos > 0, "");
 253     insert(omv, pos);
 254   }
 255 }
 256 
 257 void OopMapSort::print() {
 258   for (int i = 0; i < _count; ++i) {
 259     OopMapValue omv = _values[i];
 260     if (omv.type() == OopMapValue::oop_value || omv.type() == OopMapValue::narrowoop_value) {
 261       if (omv.reg()->is_reg()) {
 262         tty->print_cr("[%c][%d] -> reg (%ld)", omv.type() == OopMapValue::narrowoop_value ? 'n' : 'o', i, omv.reg()->value());
 263       } else {
 264         tty->print_cr("[%c][%d] -> stack (%lx)", omv.type() == OopMapValue::narrowoop_value ? 'n' : 'o', i, omv.reg()->reg2stack() * VMRegImpl::stack_slot_size);
 265       }
 266     } else {
 267       if (omv.content_reg()->is_reg()) {
 268         tty->print_cr("[d][%d] -> reg (%ld) stack (%lx)", i, omv.content_reg()->value(), omv.reg()->reg2stack() * VMRegImpl::stack_slot_size);
 269       } else if (omv.reg()->is_reg()) {
 270         tty->print_cr("[d][%d] -> stack (%lx) reg (%ld)", i, omv.content_reg()->reg2stack() * VMRegImpl::stack_slot_size, omv.reg()->value());
 271       } else {
 272         int derived_offset = omv.reg()->reg2stack() * VMRegImpl::stack_slot_size;
 273         int base_offset = omv.content_reg()->reg2stack() * VMRegImpl::stack_slot_size;
 274         tty->print_cr("[d][%d] -> stack (%x) stack (%x)", i, base_offset, derived_offset);
 275       }
 276     }
 277   }
 278 }
 279 
 280 void OopMap::copy_and_sort_data_to(address addr) const {
 281   OopMapSort sort(this);
 282   sort.sort();
 283   CompressedWriteStream* stream = new CompressedWriteStream(_write_stream->position());
 284   sort.write(stream);
 285 
 286   assert(stream->position() == write_stream()->position(), "");
 287   memcpy(addr, stream->buffer(), stream->position());
 288   //copy_data_to(addr);
 289   //sort.print();
 290 }
 291 
 292 int OopMap::heap_size() const {
 293   int size = sizeof(OopMap);
 294   int align = sizeof(void *) - 1;
 295   size += write_stream()->position();
 296   // Align to a reasonable ending point
 297   size = ((size+align) & ~align);
 298   return size;
 299 }
 300 
 301 // frame_size units are stack-slots (4 bytes) NOT intptr_t; we can name odd
 302 // slots to hold 4-byte values like ints and floats in the LP64 build.
 303 void OopMap::set_xxx(VMReg reg, OopMapValue::oop_types x, VMReg optional) {
 304 
 305   assert(reg->value() < _locs_length, "too big reg value for stack size");
 306   assert( _locs_used[reg->value()] == OopMapValue::unused_value, "cannot insert twice" );
 307   debug_only( _locs_used[reg->value()] = x; )
 308 
 309   OopMapValue o(reg, x);
 310 
 311   if(x == OopMapValue::callee_saved_value) {
 312     // This can never be a stack location, so we don't need to transform it.
 313     assert(optional->is_reg(), "Trying to callee save a stack location");
 314     o.set_content_reg(optional);
 315   } else if(x == OopMapValue::derived_oop_value) {
 316     o.set_content_reg(optional);
 317   }
 318 
 319   o.write_on(write_stream());
 320   increment_count();
 321   if (x == OopMapValue::oop_value || x == OopMapValue::narrowoop_value)
 322     increment_num_oops();
 323 }
 324 
 325 
 326 void OopMap::set_oop(VMReg reg) {
 327   set_xxx(reg, OopMapValue::oop_value, VMRegImpl::Bad());
 328 }
 329 
 330 
 331 void OopMap::set_value(VMReg reg) {
 332   // At this time, we don't need value entries in our OopMap.
 333   // set_xxx(reg, OopMapValue::live_value, VMRegImpl::Bad());
 334 }
 335 
 336 
 337 void OopMap::set_narrowoop(VMReg reg) {
 338   set_xxx(reg, OopMapValue::narrowoop_value, VMRegImpl::Bad());
 339 }
 340 
 341 
 342 void OopMap::set_callee_saved(VMReg reg, VMReg caller_machine_register ) {
 343   set_xxx(reg, OopMapValue::callee_saved_value, caller_machine_register);
 344 }
 345 
 346 
 347 void OopMap::set_derived_oop(VMReg reg, VMReg derived_from_local_register ) {
 348   if( reg == derived_from_local_register ) {
 349     // Actually an oop, derived shares storage with base,
 350     set_oop(reg);
 351   } else {
 352     set_xxx(reg, OopMapValue::derived_oop_value, derived_from_local_register);
 353   }
 354 }
 355 
 356 // OopMapSet
 357 
 358 OopMapSet::OopMapSet() {
 359   set_om_size(MinOopMapAllocation);
 360   set_om_count(0);
 361   OopMap** temp = NEW_RESOURCE_ARRAY(OopMap*, om_size());
 362   set_om_data(temp);
 363 }
 364 
 365 
 366 void OopMapSet::grow_om_data() {
 367   int new_size = om_size() * 2;
 368   OopMap** new_data = NEW_RESOURCE_ARRAY(OopMap*, new_size);
 369   memcpy(new_data,om_data(),om_size() * sizeof(OopMap*));
 370   set_om_size(new_size);
 371   set_om_data(new_data);
 372 }
 373 
 374 int OopMapSet::add_gc_map(int pc_offset, OopMap *map ) {
 375   assert(om_size() != -1,"Cannot grow a fixed OopMapSet");
 376 
 377   if(om_count() >= om_size()) {
 378     grow_om_data();
 379   }
 380   map->set_offset(pc_offset);
 381 
 382 #ifdef ASSERT
 383   if(om_count() > 0) {
 384     OopMap* last = at(om_count()-1);
 385     if (last->offset() == map->offset() ) {
 386       fatal("OopMap inserted twice");
 387     }
 388     if(last->offset() > map->offset()) {
 389       tty->print_cr( "WARNING, maps not sorted: pc[%d]=%d, pc[%d]=%d",
 390                       om_count(),last->offset(),om_count()+1,map->offset());
 391     }
 392   }
 393 #endif // ASSERT
 394 
 395   int index = om_count();
 396   set(index,map);
 397   map->_index = index;
 398   increment_count();
 399   return index;
 400 }
 401 
 402 
 403 int OopMapSet::heap_size() const {
 404   // The space we use
 405   int size = sizeof(OopMap);
 406   int align = sizeof(void *) - 1;
 407   size = ((size+align) & ~align);
 408   size += om_count() * sizeof(OopMap*);
 409 
 410   // Now add in the space needed for the indivdiual OopMaps
 411   for(int i=0; i < om_count(); i++) {
 412     size += at(i)->heap_size();
 413   }
 414   // We don't need to align this, it will be naturally pointer aligned
 415   return size;
 416 }
 417 
 418 
 419 OopMap* OopMapSet::singular_oop_map() {
 420   guarantee(om_count() == 1, "Make sure we only have a single gc point");
 421   return at(0);
 422 }
 423 
 424 
 425 OopMap* OopMapSet::find_map_at_offset(int pc_offset) const {
 426   int i, len = om_count();
 427   assert( len > 0, "must have pointer maps" );
 428 
 429   // Scan through oopmaps. Stop when current offset is either equal or greater
 430   // than the one we are looking for.
 431   for( i = 0; i < len; i++) {
 432     if( at(i)->offset() >= pc_offset )
 433       break;
 434   }
 435 
 436   assert( i < len, "oopmap not found" );
 437 
 438   OopMap* m = at(i);
 439   assert( m->offset() == pc_offset, "oopmap not found" );
 440   return m;
 441 }
 442 
 443 class AddDerivedOop : public DerivedOopClosure {
 444 public:
 445   enum { SkipNull = true, NeedsLock = true };
 446   virtual void do_derived_oop(oop* base, oop* derived) {
 447 #if !defined(TIERED) && !INCLUDE_JVMCI
 448     COMPILER1_PRESENT(ShouldNotReachHere();)
 449 #endif // !defined(TIERED) && !INCLUDE_JVMCI
 450 #if COMPILER2_OR_JVMCI
 451       DerivedPointerTable::add(derived, base);
 452 #endif // COMPILER2_OR_JVMCI
 453   }
 454 };
 455 
 456 void OopMapSet::oops_do(const frame *fr, const RegisterMap* reg_map, OopClosure* f, DerivedOopClosure* df) {
 457   // add_derived_oop: add derived oops to a table
 458   find_map(fr)->oops_do(fr, reg_map, f, df);
 459   // all_do(fr, reg_map, f, df != NULL ? df : &add_derived_oop, &do_nothing_cl);
 460 }
 461 
 462 // void OopMapSet::all_do(const frame *fr, const RegisterMap *reg_map,
 463 //                        OopClosure* oop_fn, DerivedOopClosure* derived_oop_fn,
 464 //                        OopClosure* value_fn) {
 465 //   find_map(fr)->oops_do(fr, reg_map, oop_fn, derived_oop_fn, value_fn);
 466 // }
 467 
 468 ExplodedOopMap::ExplodedOopMap(const ImmutableOopMap* oopMap) {
 469   _oopValues = copyOopMapValues(oopMap, OopMapValue::oop_value | OopMapValue::narrowoop_value, &_nrOopValues);
 470   _calleeSavedValues = copyOopMapValues(oopMap, OopMapValue::callee_saved_value, &_nrCalleeSavedValuesCount);
 471   _derivedValues = copyOopMapValues(oopMap, OopMapValue::derived_oop_value, &_nrDerivedValues);
 472 }
 473 
 474 OopMapValue* ExplodedOopMap::values(int mask) {
 475   if (mask == (OopMapValue::oop_value | OopMapValue::narrowoop_value)) {
 476     return _oopValues;
 477   } else if (mask == OopMapValue::callee_saved_value) {
 478     return _calleeSavedValues;
 479   } else if (mask == OopMapValue::derived_oop_value) {
 480     return _derivedValues;
 481   } else {
 482     guarantee(false, "new type?");
 483     return NULL;
 484   }
 485 }
 486 
 487 int ExplodedOopMap::count(int mask) {
 488   if (mask == (OopMapValue::oop_value | OopMapValue::narrowoop_value)) {
 489     return _nrOopValues;
 490   } else if (mask == OopMapValue::callee_saved_value) {
 491     return _nrCalleeSavedValuesCount;
 492   } else if (mask == OopMapValue::derived_oop_value) {
 493     return _nrDerivedValues;
 494   } else {
 495     guarantee(false, "new type?");
 496     return 0;
 497   }
 498 }
 499 
 500 OopMapValue* ExplodedOopMap::copyOopMapValues(const ImmutableOopMap* oopMap, int mask, int* nr) {
 501   OopMapValue omv;
 502   int count = 0;
 503   // We want coop and oop oop_types
 504   for (OopMapStream oms(oopMap,mask); !oms.is_done(); oms.next()) {
 505     ++count;
 506   }
 507   *nr = count;
 508 
 509   OopMapValue* values = (OopMapValue*) NEW_C_HEAP_ARRAY(unsigned char, sizeof(OopMapValue) * count, mtCode);
 510 
 511   int i = 0;
 512   for (OopMapStream oms(oopMap,mask); !oms.is_done(); oms.next()) {
 513     assert(i < count, "overflow");
 514     values[i] = oms.current();
 515     i++;
 516   }
 517 
 518   i = 0;
 519   for (OopMapStream oms(oopMap,mask); !oms.is_done(); oms.next()) {
 520     assert(i < count, "overflow");
 521     assert(values[i].equals(oms.current()), "must");
 522     i++;
 523   }
 524 
 525   return values;
 526 }
 527 
 528 // NULL, fail, success (address)
 529 void ImmutableOopMap::generate_stub(const CodeBlob* cb) const {
 530   /* The address of the ImmutableOopMap is put into the _freeze_stub and _thaw_stub 
 531    * if we can't generate the stub for some reason */
 532   if (_freeze_stub == NULL) {
 533     OopMapStubGenerator cgen(cb, *this);
 534     if (Atomic::cmpxchg((address) this, &_freeze_stub, (address) NULL) == NULL) {
 535       if (!cgen.generate()) {
 536         Atomic::store((address) this, &_thaw_stub);
 537         cgen.free();
 538         return;
 539       }
 540 
 541       Atomic::store(cgen.freeze_stub(), &_freeze_stub);
 542       Atomic::store(cgen.thaw_stub(), &_thaw_stub);
 543     }
 544   }
 545 }
 546 
 547 void ImmutableOopMap::oops_do(const frame *fr, const RegisterMap *reg_map,
 548                               OopClosure* oop_fn, DerivedOopClosure* derived_oop_fn) const {
 549   AddDerivedOop add_derived_oop;
 550   if (derived_oop_fn == NULL) {
 551     derived_oop_fn = &add_derived_oop;
 552   }
 553   OopMapDo<OopClosure, DerivedOopClosure, SkipNullValue> visitor(oop_fn, derived_oop_fn);
 554   visitor.oops_do(fr, reg_map, this);
 555 }
 556 
 557 template<typename T>
 558 static void iterate_all_do(const frame *fr, int mask, OopMapClosure* fn, const ImmutableOopMap* oopmap) {
 559   OopMapValue omv;
 560   for (T oms(oopmap,mask); !oms.is_done(); oms.next()) {
 561       omv = oms.current();
 562       fn->do_value(omv.reg(), omv.type());
 563   }
 564 }
 565 
 566 void ImmutableOopMap::all_do(const frame *fr, int mask, OopMapClosure* fn) const {
 567   if (_exploded != NULL) {
 568     iterate_all_do<ExplodedOopMapStream>(fr, mask, fn, this);
 569   } else {
 570     iterate_all_do<OopMapStream>(fr, mask, fn, this);
 571   }
 572 }
 573 
 574 template <typename T>
 575 static void update_register_map1(const ImmutableOopMap* oopmap, const frame* fr, RegisterMap* reg_map) {
 576   for (T oms(oopmap, OopMapValue::callee_saved_value); !oms.is_done(); oms.next()) {
 577     OopMapValue omv = oms.current();
 578     VMReg reg = omv.content_reg();
 579     oop* loc = fr->oopmapreg_to_location(omv.reg(), reg_map);
 580     reg_map->set_location(reg, (address) loc);
 581     //DEBUG_ONLY(nof_callee++;)
 582   }
 583 }
 584 
 585 void ImmutableOopMap::update_register_map(const frame *fr, RegisterMap *reg_map) const {
 586   // ResourceMark rm;
 587   CodeBlob* cb = fr->cb();
 588   assert(cb != NULL, "no codeblob");
 589   // Any reg might be saved by a safepoint handler (see generate_handler_blob).
 590   assert( reg_map->_update_for_id == NULL || fr->is_older(reg_map->_update_for_id),
 591          "already updated this map; do not 'update' it twice!" );
 592   debug_only(reg_map->_update_for_id = fr->id());
 593 
 594 
 595   // Check if caller must update oop argument
 596   assert((reg_map->include_argument_oops() ||
 597           !cb->caller_must_gc_arguments(reg_map->thread())),
 598          "include_argument_oops should already be set");
 599 
 600   // Scan through oopmap and find location of all callee-saved registers
 601   // (we do not do update in place, since info could be overwritten)
 602 
 603   DEBUG_ONLY(int nof_callee = 0;)
 604   if (_exploded != NULL) {
 605     update_register_map1<ExplodedOopMapStream>(this, fr, reg_map);
 606   } else {
 607     update_register_map1<OopMapStream>(this, fr, reg_map);
 608   }
 609 
 610   /*
 611   for (OopMapStream oms(this, OopMapValue::callee_saved_value); !oms.is_done(); oms.next()) {
 612     OopMapValue omv = oms.current();
 613     VMReg reg = omv.content_reg();
 614     oop* loc = fr->oopmapreg_to_location(omv.reg(), reg_map);
 615     reg_map->set_location(reg, (address) loc);
 616     DEBUG_ONLY(nof_callee++;)
 617   }
 618   */
 619 
 620   // Check that runtime stubs save all callee-saved registers
 621 #ifdef COMPILER2
 622   assert(cb == NULL || cb->is_compiled_by_c1() || cb->is_compiled_by_jvmci() || !cb->is_runtime_stub() ||
 623          (nof_callee >= SAVED_ON_ENTRY_REG_COUNT || nof_callee >= C_SAVED_ON_ENTRY_REG_COUNT),
 624          "must save all");
 625 #endif // COMPILER2
 626 }
 627 
 628 const ImmutableOopMap* OopMapSet::find_map(const frame *fr) { 
 629   return find_map(fr->cb(), fr->pc()); 
 630 }
 631 
 632 const ImmutableOopMap* OopMapSet::find_map(const CodeBlob* cb, address pc) {
 633   assert(cb != NULL, "no codeblob");
 634   const ImmutableOopMap* map = cb->oop_map_for_return_address(pc);
 635   assert(map != NULL, "no ptr map found");
 636   return map;
 637 }
 638 
 639 // Update callee-saved register info for the following frame
 640 void OopMapSet::update_register_map(const frame *fr, RegisterMap *reg_map) {
 641   find_map(fr)->update_register_map(fr, reg_map);
 642 }
 643 
 644 //=============================================================================
 645 // Non-Product code
 646 
 647 #ifndef PRODUCT
 648 
 649 bool ImmutableOopMap::has_derived_pointer() const {
 650 #if !defined(TIERED) && !INCLUDE_JVMCI
 651   COMPILER1_PRESENT(return false);
 652 #endif // !TIERED
 653 #if COMPILER2_OR_JVMCI
 654   OopMapStream oms(this,OopMapValue::derived_oop_value);
 655   return oms.is_done();
 656 #else
 657   return false;
 658 #endif // COMPILER2_OR_JVMCI
 659 }
 660 
 661 #ifndef PRODUCT
 662 void OopMapSet::trace_codeblob_maps(const frame *fr, const RegisterMap *reg_map) {
 663   // Print oopmap and regmap
 664   tty->print_cr("------ ");
 665   CodeBlob* cb = fr->cb();
 666   const ImmutableOopMapSet* maps = cb->oop_maps();
 667   const ImmutableOopMap* map = cb->oop_map_for_return_address(fr->pc());
 668   map->print();
 669   if( cb->is_nmethod() ) {
 670     nmethod* nm = (nmethod*)cb;
 671     // native wrappers have no scope data, it is implied
 672     if (nm->is_native_method()) {
 673       tty->print("bci: 0 (native)");
 674     } else {
 675       ScopeDesc* scope  = nm->scope_desc_at(fr->pc());
 676       tty->print("bci: %d ",scope->bci());
 677     }
 678   }
 679   tty->cr();
 680   fr->print_on(tty);
 681   tty->print("     ");
 682   cb->print_value_on(tty);  tty->cr();
 683   if (reg_map != NULL) {
 684     reg_map->print();
 685   }
 686   tty->print_cr("------ ");
 687 
 688 }
 689 #endif // PRODUCT
 690 
 691 
 692 #endif //PRODUCT
 693 
 694 // Printing code is present in product build for -XX:+PrintAssembly.
 695 
 696 static
 697 void print_register_type(OopMapValue::oop_types x, VMReg optional,
 698                          outputStream* st) {
 699   switch( x ) {
 700   case OopMapValue::oop_value:
 701     st->print("Oop");
 702     break;
 703   case OopMapValue::narrowoop_value:
 704     st->print("NarrowOop");
 705     break;
 706   case OopMapValue::callee_saved_value:
 707     st->print("Callers_");
 708     optional->print_on(st);
 709     break;
 710   case OopMapValue::derived_oop_value:
 711     st->print("Derived_oop_");
 712     optional->print_on(st);
 713     break;
 714   default:
 715     ShouldNotReachHere();
 716   }
 717 }
 718 
 719 void OopMapValue::print_on(outputStream* st) const {
 720   reg()->print_on(st);
 721   st->print("=");
 722   print_register_type(type(),content_reg(),st);
 723   st->print(" ");
 724 }
 725 
 726 void OopMapValue::print() const { print_on(tty); }
 727 
 728 void ImmutableOopMap::print_on(outputStream* st) const {
 729   OopMapValue omv;
 730   st->print("ImmutableOopMap {");
 731   for(OopMapStream oms(this); !oms.is_done(); oms.next()) {
 732     omv = oms.current();
 733     omv.print_on(st);
 734   }
 735   st->print("}");
 736 }
 737 
 738 void ImmutableOopMap::print() const { print_on(tty); }
 739 
 740 void OopMap::print_on(outputStream* st) const {
 741   OopMapValue omv;
 742   st->print("OopMap {");
 743   for(OopMapStream oms((OopMap*)this); !oms.is_done(); oms.next()) {
 744     omv = oms.current();
 745     omv.print_on(st);
 746   }
 747   // Print hex offset in addition.
 748   st->print("off=%d/0x%x}", (int) offset(), (int) offset());
 749 }
 750 
 751 void OopMap::print() const { print_on(tty); }
 752 
 753 void ImmutableOopMapSet::print_on(outputStream* st) const {
 754   const ImmutableOopMap* last = NULL;
 755   const int len = count();
 756 
 757   st->print_cr("ImmutableOopMapSet contains %d OopMaps", len);
 758 
 759   for (int i = 0; i < len; i++) {
 760     const ImmutableOopMapPair* pair = pair_at(i);
 761     const ImmutableOopMap* map = pair->get_from(this);
 762     if (map != last) {
 763       st->cr();
 764       map->print_on(st);
 765       st->print(" pc offsets: ");
 766     }
 767     last = map;
 768     st->print("%d ", pair->pc_offset());
 769   }
 770   st->cr();
 771 }
 772 
 773 void ImmutableOopMapSet::print() const { print_on(tty); }
 774 
 775 void OopMapSet::print_on(outputStream* st) const {
 776   const int len = om_count();
 777 
 778   st->print_cr("OopMapSet contains %d OopMaps", len);
 779 
 780   for( int i = 0; i < len; i++) {
 781     OopMap* m = at(i);
 782     st->print_cr("#%d ",i);
 783     m->print_on(st);
 784     st->cr();
 785   }
 786   st->cr();
 787 }
 788 
 789 void OopMapSet::print() const { print_on(tty); }
 790 
 791 bool OopMap::equals(const OopMap* other) const {
 792   if (other->_omv_count != _omv_count) {
 793     return false;
 794   }
 795   if (other->write_stream()->position() != write_stream()->position()) {
 796     return false;
 797   }
 798   if (memcmp(other->write_stream()->buffer(), write_stream()->buffer(), write_stream()->position()) != 0) {
 799     return false;
 800   }
 801   return true;
 802 }
 803 
 804 int ImmutableOopMapSet::find_slot_for_offset(int pc_offset) const {
 805   ImmutableOopMapPair* pairs = get_pairs();
 806 
 807   for (int i = 0; i < _count; ++i) {
 808     if (pairs[i].pc_offset() >= pc_offset) {
 809       ImmutableOopMapPair* last = &pairs[i];
 810       assert(last->pc_offset() == pc_offset, "oopmap not found");
 811       return i;
 812     }
 813   }
 814 
 815   guarantee(false, "failed to find oopmap for pc");
 816   return -1;
 817 }
 818 
 819 const ImmutableOopMap* ImmutableOopMapSet::find_map_at_offset(int pc_offset) const {
 820   ImmutableOopMapPair* pairs = get_pairs();
 821   ImmutableOopMapPair* last  = NULL;
 822 
 823   for (int i = 0; i < _count; ++i) {
 824     if (pairs[i].pc_offset() >= pc_offset) {
 825       last = &pairs[i];
 826       break;
 827     }
 828   }
 829 
 830   // Heal Coverity issue: potential index out of bounds access.
 831   guarantee(last != NULL, "last may not be null");
 832   assert(last->pc_offset() == pc_offset, "oopmap not found");
 833   return last->get_from(this);
 834 }
 835 
 836 ImmutableOopMap::ImmutableOopMap(const OopMap* oopmap) : _exploded(NULL), _freeze_stub(NULL), _thaw_stub(NULL), _count(oopmap->count()), _num_oops(oopmap->num_oops()) {
 837   _num_oops = oopmap->num_oops();
 838   address addr = data_addr();
 839   //oopmap->copy_data_to(addr);
 840   oopmap->copy_and_sort_data_to(addr);
 841 }
 842 
 843 #ifdef ASSERT
 844 int ImmutableOopMap::nr_of_bytes() const {
 845   OopMapStream oms(this);
 846 
 847   while (!oms.is_done()) {
 848     oms.next();
 849   }
 850   return sizeof(ImmutableOopMap) + oms.stream_position();
 851 }
 852 #endif
 853 
 854 ImmutableOopMapBuilder::ImmutableOopMapBuilder(const OopMapSet* set) : _set(set), _empty(NULL), _last(NULL), _empty_offset(-1), _last_offset(-1), _offset(0), _required(-1), _new_set(NULL) {
 855   _mapping = NEW_RESOURCE_ARRAY(Mapping, _set->size());
 856 }
 857 
 858 int ImmutableOopMapBuilder::size_for(const OopMap* map) const {
 859   return align_up((int)sizeof(ImmutableOopMap) + map->data_size(), 8);
 860 }
 861 
 862 int ImmutableOopMapBuilder::heap_size() {
 863   int base = sizeof(ImmutableOopMapSet);
 864   base = align_up(base, 8);
 865 
 866   // all of ours pc / offset pairs
 867   int pairs = _set->size() * sizeof(ImmutableOopMapPair);
 868   pairs = align_up(pairs, 8);
 869 
 870   for (int i = 0; i < _set->size(); ++i) {
 871     int size = 0;
 872     OopMap* map = _set->at(i);
 873 
 874     if (is_empty(map)) {
 875       /* only keep a single empty map in the set */
 876       if (has_empty()) {
 877         _mapping[i].set(Mapping::OOPMAP_EMPTY, _empty_offset, 0, map, _empty);
 878       } else {
 879         _empty_offset = _offset;
 880         _empty = map;
 881         size = size_for(map);
 882         _mapping[i].set(Mapping::OOPMAP_NEW, _offset, size, map);
 883       }
 884     } else if (is_last_duplicate(map)) {
 885       /* if this entry is identical to the previous one, just point it there */
 886       _mapping[i].set(Mapping::OOPMAP_DUPLICATE, _last_offset, 0, map, _last);
 887     } else {
 888       /* not empty, not an identical copy of the previous entry */
 889       size = size_for(map);
 890       _mapping[i].set(Mapping::OOPMAP_NEW, _offset, size, map);
 891       _last_offset = _offset;
 892       _last = map;
 893     }
 894 
 895     assert(_mapping[i]._map == map, "check");
 896     _offset += size;
 897   }
 898 
 899   int total = base + pairs + _offset;
 900   DEBUG_ONLY(total += 8);
 901   _required = total;
 902   return total;
 903 }
 904 
 905 void ImmutableOopMapBuilder::fill_pair(ImmutableOopMapPair* pair, const OopMap* map, int offset, const ImmutableOopMapSet* set) {
 906   assert(offset < set->nr_of_bytes(), "check");
 907   new ((address) pair) ImmutableOopMapPair(map->offset(), offset);
 908 }
 909 
 910 int ImmutableOopMapBuilder::fill_map(ImmutableOopMapPair* pair, const OopMap* map, int offset, const ImmutableOopMapSet* set) {
 911   fill_pair(pair, map, offset, set);
 912   address addr = (address) pair->get_from(_new_set); // location of the ImmutableOopMap
 913 
 914   new (addr) ImmutableOopMap(map);
 915   return size_for(map);
 916 }
 917 
 918 void ImmutableOopMapBuilder::fill(ImmutableOopMapSet* set, int sz) {
 919   ImmutableOopMapPair* pairs = set->get_pairs();
 920 
 921   for (int i = 0; i < set->count(); ++i) {
 922     const OopMap* map = _mapping[i]._map;
 923     ImmutableOopMapPair* pair = NULL;
 924     int size = 0;
 925 
 926     if (_mapping[i]._kind == Mapping::OOPMAP_NEW) {
 927       size = fill_map(&pairs[i], map, _mapping[i]._offset, set);
 928     } else if (_mapping[i]._kind == Mapping::OOPMAP_DUPLICATE || _mapping[i]._kind == Mapping::OOPMAP_EMPTY) {
 929       fill_pair(&pairs[i], map, _mapping[i]._offset, set);
 930     }
 931 
 932     const ImmutableOopMap* nv = set->find_map_at_offset(map->offset());
 933     //assert(memcmp(map->data(), nv->data_addr(), map->data_size()) == 0, "check identity");
 934   }
 935 }
 936 
 937 #ifdef ASSERT
 938 void ImmutableOopMapBuilder::verify(address buffer, int size, const ImmutableOopMapSet* set) {
 939   for (int i = 0; i < 8; ++i) {
 940     assert(buffer[size - 8 + i] == (unsigned char) 0xff, "overwritten memory check");
 941   }
 942 
 943   for (int i = 0; i < set->count(); ++i) {
 944     const ImmutableOopMapPair* pair = set->pair_at(i);
 945     assert(pair->oopmap_offset() < set->nr_of_bytes(), "check size");
 946     const ImmutableOopMap* map = pair->get_from(set);
 947     int nr_of_bytes = map->nr_of_bytes();
 948     assert(pair->oopmap_offset() + nr_of_bytes <= set->nr_of_bytes(), "check size + size");
 949   }
 950 }
 951 #endif
 952 
 953 ImmutableOopMapSet* ImmutableOopMapBuilder::generate_into(address buffer) {
 954   DEBUG_ONLY(memset(&buffer[_required-8], 0xff, 8));
 955 
 956   _new_set = new (buffer) ImmutableOopMapSet(_set, _required);
 957   fill(_new_set, _required);
 958 
 959   DEBUG_ONLY(verify(buffer, _required, _new_set));
 960 
 961   return _new_set;
 962 }
 963 
 964 ImmutableOopMapSet* ImmutableOopMapBuilder::build() {
 965   _required = heap_size();
 966 
 967   // We need to allocate a chunk big enough to hold the ImmutableOopMapSet and all of its ImmutableOopMaps
 968   address buffer = (address) NEW_C_HEAP_ARRAY(unsigned char, _required, mtCode);
 969   return generate_into(buffer);
 970 }
 971 
 972 ImmutableOopMapSet* ImmutableOopMapSet::build_from(const OopMapSet* oopmap_set) {
 973   ResourceMark mark;
 974   ImmutableOopMapBuilder builder(oopmap_set);
 975   return builder.build();
 976 }
 977 
 978 
 979 //------------------------------DerivedPointerTable---------------------------
 980 
 981 #if COMPILER2_OR_JVMCI
 982 
 983 class DerivedPointerTable::Entry : public CHeapObj<mtCompiler> {
 984   oop* _location;   // Location of derived pointer, also pointing to base
 985   intptr_t _offset; // Offset from base pointer
 986   Entry* volatile _next;
 987 
 988   static Entry* volatile* next_ptr(Entry& entry) { return &entry._next; }
 989 
 990 public:
 991   Entry(oop* location, intptr_t offset) :
 992     _location(location), _offset(offset), _next(NULL) {}
 993 
 994   oop* location() const { return _location; }
 995   intptr_t offset() const { return _offset; }
 996   Entry* next() const { return _next; }
 997 
 998   typedef LockFreeStack<Entry, &next_ptr> List;
 999   static List* _list;
1000 };
1001 
1002 DerivedPointerTable::Entry::List* DerivedPointerTable::Entry::_list = NULL;
1003 bool DerivedPointerTable::_active = false;
1004 
1005 bool DerivedPointerTable::is_empty() {
1006   return Entry::_list == NULL || Entry::_list->empty();
1007 }
1008 
1009 void DerivedPointerTable::clear() {
1010   // The first time, we create the list.  Otherwise it should be
1011   // empty.  If not, then we have probably forgotton to call
1012   // update_pointers after last GC/Scavenge.
1013   assert (!_active, "should not be active");
1014   assert(is_empty(), "table not empty");
1015   if (Entry::_list == NULL) {
1016     void* mem = NEW_C_HEAP_OBJ(Entry::List, mtCompiler);
1017     Entry::_list = ::new (mem) Entry::List();
1018   }
1019   _active = true;
1020 }
1021 
1022 // Returns value of location as an int
1023 inline intptr_t value_of_loc(oop *pointer) {
1024   return cast_from_oop<intptr_t>((*pointer));
1025 }
1026 
1027 void DerivedPointerTable::add(oop *derived_loc, oop *base_loc) {
1028   assert(Universe::heap()->is_in_or_null(*base_loc), "not an oop");
1029   assert(derived_loc != base_loc, "Base and derived in same location");
1030   if (_active) {
1031     assert(*derived_loc != (oop)base_loc, "location already added");
1032     assert(Entry::_list != NULL, "list must exist");
1033     intptr_t offset = value_of_loc(derived_loc) - value_of_loc(base_loc);
1034     // This assert is invalid because derived pointers can be
1035     // arbitrarily far away from their base.
1036     // assert(offset >= -1000000, "wrong derived pointer info");
1037 
1038     if (TraceDerivedPointers) {
1039       tty->print_cr(
1040         "Add derived pointer@" INTPTR_FORMAT
1041         " - Derived: " INTPTR_FORMAT
1042         " Base: " INTPTR_FORMAT " (@" INTPTR_FORMAT ") (Offset: " INTX_FORMAT ")",
1043         p2i(derived_loc), p2i((address)*derived_loc), p2i((address)*base_loc), p2i(base_loc), offset
1044       );
1045     }
1046     // Set derived oop location to point to base.
1047     *derived_loc = (oop)base_loc;
1048     Entry* entry = new Entry(derived_loc, offset);
1049     Entry::_list->push(*entry);
1050   }
1051 }
1052 
1053 void DerivedPointerTable::update_pointers() {
1054   assert(Entry::_list != NULL, "list must exist");
1055   Entry* entries = Entry::_list->pop_all();
1056   while (entries != NULL) {
1057     Entry* entry = entries;
1058     entries = entry->next();
1059     oop* derived_loc = entry->location();
1060     intptr_t offset  = entry->offset();
1061     // The derived oop was setup to point to location of base
1062     oop base = **(oop**)derived_loc;
1063     assert(Universe::heap()->is_in_or_null(base), "must be an oop");
1064 
1065     *derived_loc = (oop)(((address)base) + offset);
1066     assert(value_of_loc(derived_loc) - value_of_loc(&base) == offset, "sanity check");
1067 
1068     if (TraceDerivedPointers) {
1069       tty->print_cr("Updating derived pointer@" INTPTR_FORMAT
1070                     " - Derived: " INTPTR_FORMAT "  Base: " INTPTR_FORMAT " (Offset: " INTX_FORMAT ")",
1071           p2i(derived_loc), p2i((address)*derived_loc), p2i((address)base), offset);
1072     }
1073 
1074     // Delete entry
1075     delete entry;
1076   }
1077   assert(Entry::_list->empty(), "invariant");
1078   _active = false;
1079 }
1080 
1081 #endif // COMPILER2_OR_JVMCI