1 /*
   2  * Copyright (c) 1997, 2011, 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 #ifndef SHARE_VM_UTILITIES_GROWABLEARRAY_HPP
  26 #define SHARE_VM_UTILITIES_GROWABLEARRAY_HPP
  27 
  28 #include "memory/allocation.hpp"
  29 #include "memory/allocation.inline.hpp"
  30 #include "utilities/debug.hpp"
  31 #include "utilities/globalDefinitions.hpp"
  32 #include "utilities/top.hpp"
  33 
  34 // A growable array.
  35 
  36 /*************************************************************************/
  37 /*                                                                       */
  38 /*     WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING   */
  39 /*                                                                       */
  40 /* Should you use GrowableArrays to contain handles you must be certain  */
  41 /* the the GrowableArray does not outlive the HandleMark that contains   */
  42 /* the handles. Since GrowableArrays are typically resource allocated    */
  43 /* the following is an example of INCORRECT CODE,                        */
  44 /*                                                                       */
  45 /* ResourceMark rm;                                                      */
  46 /* GrowableArray<Handle>* arr = new GrowableArray<Handle>(size);         */
  47 /* if (blah) {                                                           */
  48 /*    while (...) {                                                      */
  49 /*      HandleMark hm;                                                   */
  50 /*      ...                                                              */
  51 /*      Handle h(THREAD, some_oop);                                      */
  52 /*      arr->append(h);                                                  */
  53 /*    }                                                                  */
  54 /* }                                                                     */
  55 /* if (arr->length() != 0 ) {                                            */
  56 /*    oop bad_oop = arr->at(0)(); // Handle is BAD HERE.                 */
  57 /*    ...                                                                */
  58 /* }                                                                     */
  59 /*                                                                       */
  60 /* If the GrowableArrays you are creating is C_Heap allocated then it    */
  61 /* hould not old handles since the handles could trivially try and       */
  62 /* outlive their HandleMark. In some situations you might need to do     */
  63 /* this and it would be legal but be very careful and see if you can do  */
  64 /* the code in some other manner.                                        */
  65 /*                                                                       */
  66 /*************************************************************************/
  67 
  68 // To call default constructor the placement operator new() is used.
  69 // It should be empty (it only returns the passed void* pointer).
  70 // The definition of placement operator new(size_t, void*) in the <new>.
  71 
  72 #include <new>
  73 
  74 // Need the correct linkage to call qsort without warnings
  75 extern "C" {
  76   typedef int (*_sort_Fn)(const void *, const void *);
  77 }
  78 
  79 class GenericGrowableArray : public ResourceObj {
  80   friend class VMStructs;
  81 
  82  protected:
  83   int    _len;          // current length
  84   int    _max;          // maximum length
  85   Arena* _arena;        // Indicates where allocation occurs:
  86                         //   0 means default ResourceArea
  87                         //   1 means on C heap
  88                         //   otherwise, allocate in _arena
  89 #ifdef ASSERT
  90   int    _nesting;      // resource area nesting at creation
  91   void   set_nesting();
  92   void   check_nesting();
  93 #else
  94 #define  set_nesting();
  95 #define  check_nesting();
  96 #endif
  97 
  98   // Where are we going to allocate memory?
  99   bool on_C_heap() { return _arena == (Arena*)1; }
 100   bool on_stack () { return _arena == NULL;      }
 101   bool on_arena () { return _arena >  (Arena*)1;  }
 102 
 103   // This GA will use the resource stack for storage if c_heap==false,
 104   // Else it will use the C heap.  Use clear_and_deallocate to avoid leaks.
 105   GenericGrowableArray(int initial_size, int initial_len, bool c_heap) {
 106     _len = initial_len;
 107     _max = initial_size;
 108     assert(_len >= 0 && _len <= _max, "initial_len too big");
 109     _arena = (c_heap ? (Arena*)1 : NULL);
 110     set_nesting();
 111     assert(!on_C_heap() || allocated_on_C_heap(), "growable array must be on C heap if elements are");
 112     assert(!on_stack() ||
 113            (allocated_on_res_area() || allocated_on_stack()),
 114            "growable array must be on stack if elements are not on arena and not on C heap");
 115   }
 116 
 117   // This GA will use the given arena for storage.
 118   // Consider using new(arena) GrowableArray<T> to allocate the header.
 119   GenericGrowableArray(Arena* arena, int initial_size, int initial_len) {
 120     _len = initial_len;
 121     _max = initial_size;
 122     assert(_len >= 0 && _len <= _max, "initial_len too big");
 123     _arena = arena;
 124     assert(on_arena(), "arena has taken on reserved value 0 or 1");
 125     // Relax next assert to allow object allocation on resource area,
 126     // on stack or embedded into an other object.
 127     assert(allocated_on_arena() || allocated_on_stack(),
 128            "growable array must be on arena or on stack if elements are on arena");
 129   }
 130 
 131   void* raw_allocate(int elementSize);
 132 
 133   // some uses pass the Thread explicitly for speed (4990299 tuning)
 134   void* raw_allocate(Thread* thread, int elementSize) {
 135     assert(on_stack(), "fast ResourceObj path only");
 136     return (void*)resource_allocate_bytes(thread, elementSize * _max);
 137   }
 138 };
 139 
 140 template<class E> class GrowableArray : public GenericGrowableArray {
 141   friend class VMStructs;
 142 
 143  private:
 144   E*     _data;         // data array
 145 
 146   void grow(int j);
 147   void raw_at_put_grow(int i, const E& p, const E& fill);
 148   void  clear_and_deallocate();
 149  public:
 150   GrowableArray(Thread* thread, int initial_size) : GenericGrowableArray(initial_size, 0, false) {
 151     _data = (E*)raw_allocate(thread, sizeof(E));
 152     for (int i = 0; i < _max; i++) ::new ((void*)&_data[i]) E();
 153   }
 154 
 155   GrowableArray(int initial_size, bool C_heap = false) : GenericGrowableArray(initial_size, 0, C_heap) {
 156     _data = (E*)raw_allocate(sizeof(E));
 157     for (int i = 0; i < _max; i++) ::new ((void*)&_data[i]) E();
 158   }
 159 
 160   GrowableArray(int initial_size, int initial_len, const E& filler, bool C_heap = false) : GenericGrowableArray(initial_size, initial_len, C_heap) {
 161     _data = (E*)raw_allocate(sizeof(E));
 162     int i = 0;
 163     for (; i < _len; i++) ::new ((void*)&_data[i]) E(filler);
 164     for (; i < _max; i++) ::new ((void*)&_data[i]) E();
 165   }
 166 
 167   GrowableArray(Arena* arena, int initial_size, int initial_len, const E& filler) : GenericGrowableArray(arena, initial_size, initial_len) {
 168     _data = (E*)raw_allocate(sizeof(E));
 169     int i = 0;
 170     for (; i < _len; i++) ::new ((void*)&_data[i]) E(filler);
 171     for (; i < _max; i++) ::new ((void*)&_data[i]) E();
 172   }
 173 
 174   GrowableArray() : GenericGrowableArray(2, 0, false) {
 175     _data = (E*)raw_allocate(sizeof(E));
 176     ::new ((void*)&_data[0]) E();
 177     ::new ((void*)&_data[1]) E();
 178   }
 179 
 180                                 // Does nothing for resource and arena objects
 181   ~GrowableArray()              { if (on_C_heap()) clear_and_deallocate(); }
 182 
 183   void  clear()                 { _len = 0; }
 184   int   length() const          { return _len; }
 185   void  trunc_to(int l)         { assert(l <= _len,"cannot increase length"); _len = l; }
 186   bool  is_empty() const        { return _len == 0; }
 187   bool  is_nonempty() const     { return _len != 0; }
 188   bool  is_full() const         { return _len == _max; }
 189   DEBUG_ONLY(E* data_addr() const      { return _data; })
 190 
 191   void print();
 192 
 193   int append(const E& elem) {
 194     check_nesting();
 195     if (_len == _max) grow(_len);
 196     int idx = _len++;
 197     _data[idx] = elem;
 198     return idx;
 199   }
 200 
 201   void append_if_missing(const E& elem) {
 202     if (!contains(elem)) append(elem);
 203   }
 204 
 205   E at(int i) const {
 206     assert(0 <= i && i < _len, "illegal index");
 207     return _data[i];
 208   }
 209 
 210   E* adr_at(int i) const {
 211     assert(0 <= i && i < _len, "illegal index");
 212     return &_data[i];
 213   }
 214 
 215   E first() const {
 216     assert(_len > 0, "empty list");
 217     return _data[0];
 218   }
 219 
 220   E top() const {
 221     assert(_len > 0, "empty list");
 222     return _data[_len-1];
 223   }
 224 
 225   void push(const E& elem) { append(elem); }
 226 
 227   E pop() {
 228     assert(_len > 0, "empty list");
 229     return _data[--_len];
 230   }
 231 
 232   void at_put(int i, const E& elem) {
 233     assert(0 <= i && i < _len, "illegal index");
 234     _data[i] = elem;
 235   }
 236 
 237   E at_grow(int i, const E& fill = E()) {
 238     assert(0 <= i, "negative index");
 239     check_nesting();
 240     if (i >= _len) {
 241       if (i >= _max) grow(i);
 242       for (int j = _len; j <= i; j++)
 243         _data[j] = fill;
 244       _len = i+1;
 245     }
 246     return _data[i];
 247   }
 248 
 249   void at_put_grow(int i, const E& elem, const E& fill = E()) {
 250     assert(0 <= i, "negative index");
 251     check_nesting();
 252     raw_at_put_grow(i, elem, fill);
 253   }
 254 
 255   bool contains(const E& elem) const {
 256     for (int i = 0; i < _len; i++) {
 257       if (_data[i] == elem) return true;
 258     }
 259     return false;
 260   }
 261 
 262   int  find(const E& elem) const {
 263     for (int i = 0; i < _len; i++) {
 264       if (_data[i] == elem) return i;
 265     }
 266     return -1;
 267   }
 268 
 269   int  find(void* token, bool f(void*, E)) const {
 270     for (int i = 0; i < _len; i++) {
 271       if (f(token, _data[i])) return i;
 272     }
 273     return -1;
 274   }
 275 
 276   int  find_at_end(void* token, bool f(void*, E)) const {
 277     // start at the end of the array
 278     for (int i = _len-1; i >= 0; i--) {
 279       if (f(token, _data[i])) return i;
 280     }
 281     return -1;
 282   }
 283 
 284   void remove(const E& elem) {
 285     for (int i = 0; i < _len; i++) {
 286       if (_data[i] == elem) {
 287         for (int j = i + 1; j < _len; j++) _data[j-1] = _data[j];
 288         _len--;
 289         return;
 290       }
 291     }
 292     ShouldNotReachHere();
 293   }
 294 
 295   void remove_at(int index) {
 296     assert(0 <= index && index < _len, "illegal index");
 297     for (int j = index + 1; j < _len; j++) _data[j-1] = _data[j];
 298     _len--;
 299   }
 300 
 301   // inserts the given element before the element at index i
 302   void insert_before(const int idx, const E& elem) {
 303     check_nesting();
 304     if (_len == _max) grow(_len);
 305     for (int j = _len - 1; j >= idx; j--) {
 306       _data[j + 1] = _data[j];
 307     }
 308     _len++;
 309     _data[idx] = elem;
 310   }
 311 
 312   void appendAll(const GrowableArray<E>* l) {
 313     for (int i = 0; i < l->_len; i++) {
 314       raw_at_put_grow(_len, l->_data[i], 0);
 315     }
 316   }
 317 
 318   void sort(int f(E*,E*)) {
 319     qsort(_data, length(), sizeof(E), (_sort_Fn)f);
 320   }
 321   // sort by fixed-stride sub arrays:
 322   void sort(int f(E*,E*), int stride) {
 323     qsort(_data, length() / stride, sizeof(E) * stride, (_sort_Fn)f);
 324   }
 325 };
 326 
 327 // Global GrowableArray methods (one instance in the library per each 'E' type).
 328 
 329 template<class E> void GrowableArray<E>::grow(int j) {
 330     // grow the array by doubling its size (amortized growth)
 331     int old_max = _max;
 332     if (_max == 0) _max = 1; // prevent endless loop
 333     while (j >= _max) _max = _max*2;
 334     // j < _max
 335     E* newData = (E*)raw_allocate(sizeof(E));
 336     int i = 0;
 337     for (     ; i < _len; i++) ::new ((void*)&newData[i]) E(_data[i]);
 338     for (     ; i < _max; i++) ::new ((void*)&newData[i]) E();
 339     for (i = 0; i < old_max; i++) _data[i].~E();
 340     if (on_C_heap() && _data != NULL) {
 341       FreeHeap(_data);
 342     }
 343     _data = newData;
 344 }
 345 
 346 template<class E> void GrowableArray<E>::raw_at_put_grow(int i, const E& p, const E& fill) {
 347     if (i >= _len) {
 348       if (i >= _max) grow(i);
 349       for (int j = _len; j < i; j++)
 350         _data[j] = fill;
 351       _len = i+1;
 352     }
 353     _data[i] = p;
 354 }
 355 
 356 // This function clears and deallocate the data in the growable array that
 357 // has been allocated on the C heap.  It's not public - called by the
 358 // destructor.
 359 template<class E> void GrowableArray<E>::clear_and_deallocate() {
 360     assert(on_C_heap(),
 361            "clear_and_deallocate should only be called when on C heap");
 362     clear();
 363     if (_data != NULL) {
 364       for (int i = 0; i < _max; i++) _data[i].~E();
 365       FreeHeap(_data);
 366       _data = NULL;
 367     }
 368 }
 369 
 370 template<class E> void GrowableArray<E>::print() {
 371     tty->print("Growable Array " INTPTR_FORMAT, this);
 372     tty->print(": length %ld (_max %ld) { ", _len, _max);
 373     for (int i = 0; i < _len; i++) tty->print(INTPTR_FORMAT " ", *(intptr_t*)&(_data[i]));
 374     tty->print("}\n");
 375 }
 376 
 377 #endif // SHARE_VM_UTILITIES_GROWABLEARRAY_HPP