Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/libadt/dict.cpp
32285 views
/*1* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "libadt/dict.hpp"26#include "memory/allocation.inline.hpp"27#include "memory/resourceArea.hpp"28#include "runtime/thread.hpp"2930// Dictionaries - An Abstract Data Type3132// %%%%% includes not needed with AVM framework - Ungar3334// #include "port.hpp"35//IMPLEMENTATION36// #include "dict.hpp"3738#include <assert.h>3940PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC4142// The iostream is not needed and it gets confused for gcc by the43// define of bool.44//45// #include <iostream.h>4647//------------------------------data-----------------------------------------48// String hash tables49#define MAXID 2050static byte initflag = 0; // True after 1st initialization51static const char shft[MAXID] = {1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6};52static short xsum[MAXID];5354//------------------------------bucket---------------------------------------55class bucket : public ResourceObj {56public:57uint _cnt, _max; // Size of bucket58void **_keyvals; // Array of keys and values59};6061//------------------------------Dict-----------------------------------------62// The dictionary is kept has a hash table. The hash table is a even power63// of two, for nice modulo operations. Each bucket in the hash table points64// to a linear list of key-value pairs; each key & value is just a (void *).65// The list starts with a count. A hash lookup finds the list head, then a66// simple linear scan finds the key. If the table gets too full, it's67// doubled in size; the total amount of EXTRA times all hash functions are68// computed for the doubling is no more than the current size - thus the69// doubling in size costs no more than a constant factor in speed.70Dict::Dict(CmpKey initcmp, Hash inithash) : _hash(inithash), _cmp(initcmp),71_arena(Thread::current()->resource_area()) {72int i;7374// Precompute table of null character hashes75if( !initflag ) { // Not initializated yet?76xsum[0] = (1<<shft[0])+1; // Initialize77for(i=1; i<MAXID; i++) {78xsum[i] = (1<<shft[i])+1+xsum[i-1];79}80initflag = 1; // Never again81}8283_size = 16; // Size is a power of 284_cnt = 0; // Dictionary is empty85_bin = (bucket*)_arena->Amalloc_4(sizeof(bucket)*_size);86memset(_bin,0,sizeof(bucket)*_size);87}8889Dict::Dict(CmpKey initcmp, Hash inithash, Arena *arena, int size)90: _hash(inithash), _cmp(initcmp), _arena(arena) {91int i;9293// Precompute table of null character hashes94if( !initflag ) { // Not initializated yet?95xsum[0] = (1<<shft[0])+1; // Initialize96for(i=1; i<MAXID; i++) {97xsum[i] = (1<<shft[i])+1+xsum[i-1];98}99initflag = 1; // Never again100}101102i=16;103while( i < size ) i <<= 1;104_size = i; // Size is a power of 2105_cnt = 0; // Dictionary is empty106_bin = (bucket*)_arena->Amalloc_4(sizeof(bucket)*_size);107memset(_bin,0,sizeof(bucket)*_size);108}109110//------------------------------~Dict------------------------------------------111// Delete an existing dictionary.112Dict::~Dict() {113/*114tty->print("~Dict %d/%d: ",_cnt,_size);115for( uint i=0; i < _size; i++) // For complete new table do116tty->print("%d ",_bin[i]._cnt);117tty->print("\n");*/118/*for( uint i=0; i<_size; i++ ) {119FREE_FAST( _bin[i]._keyvals );120} */121}122123//------------------------------Clear----------------------------------------124// Zap to empty; ready for re-use125void Dict::Clear() {126_cnt = 0; // Empty contents127for( uint i=0; i<_size; i++ )128_bin[i]._cnt = 0; // Empty buckets, but leave allocated129// Leave _size & _bin alone, under the assumption that dictionary will130// grow to this size again.131}132133//------------------------------doubhash---------------------------------------134// Double hash table size. If can't do so, just suffer. If can, then run135// thru old hash table, moving things to new table. Note that since hash136// table doubled, exactly 1 new bit is exposed in the mask - so everything137// in the old table ends up on 1 of two lists in the new table; a hi and a138// lo list depending on the value of the bit.139void Dict::doubhash(void) {140uint oldsize = _size;141_size <<= 1; // Double in size142_bin = (bucket*)_arena->Arealloc( _bin, sizeof(bucket)*oldsize, sizeof(bucket)*_size );143memset( &_bin[oldsize], 0, oldsize*sizeof(bucket) );144// Rehash things to spread into new table145for( uint i=0; i < oldsize; i++) { // For complete OLD table do146bucket *b = &_bin[i]; // Handy shortcut for _bin[i]147if( !b->_keyvals ) continue; // Skip empties fast148149bucket *nb = &_bin[i+oldsize]; // New bucket shortcut150uint j = b->_max; // Trim new bucket to nearest power of 2151while( j > b->_cnt ) j >>= 1; // above old bucket _cnt152if( !j ) j = 1; // Handle zero-sized buckets153nb->_max = j<<1;154// Allocate worst case space for key-value pairs155nb->_keyvals = (void**)_arena->Amalloc_4( sizeof(void *)*nb->_max*2 );156uint nbcnt = 0;157158for( j=0; j<b->_cnt; j++ ) { // Rehash all keys in this bucket159void *key = b->_keyvals[j+j];160if( (_hash( key ) & (_size-1)) != i ) { // Moving to hi bucket?161nb->_keyvals[nbcnt+nbcnt] = key;162nb->_keyvals[nbcnt+nbcnt+1] = b->_keyvals[j+j+1];163nb->_cnt = nbcnt = nbcnt+1;164b->_cnt--; // Remove key/value from lo bucket165b->_keyvals[j+j ] = b->_keyvals[b->_cnt+b->_cnt ];166b->_keyvals[j+j+1] = b->_keyvals[b->_cnt+b->_cnt+1];167j--; // Hash compacted element also168}169} // End of for all key-value pairs in bucket170} // End of for all buckets171172173}174175//------------------------------Dict-----------------------------------------176// Deep copy a dictionary.177Dict::Dict( const Dict &d ) : _size(d._size), _cnt(d._cnt), _hash(d._hash),_cmp(d._cmp), _arena(d._arena) {178_bin = (bucket*)_arena->Amalloc_4(sizeof(bucket)*_size);179memcpy( _bin, d._bin, sizeof(bucket)*_size );180for( uint i=0; i<_size; i++ ) {181if( !_bin[i]._keyvals ) continue;182_bin[i]._keyvals=(void**)_arena->Amalloc_4( sizeof(void *)*_bin[i]._max*2);183memcpy( _bin[i]._keyvals, d._bin[i]._keyvals,_bin[i]._cnt*2*sizeof(void*));184}185}186187//------------------------------Dict-----------------------------------------188// Deep copy a dictionary.189Dict &Dict::operator =( const Dict &d ) {190if( _size < d._size ) { // If must have more buckets191_arena = d._arena;192_bin = (bucket*)_arena->Arealloc( _bin, sizeof(bucket)*_size, sizeof(bucket)*d._size );193memset( &_bin[_size], 0, (d._size-_size)*sizeof(bucket) );194_size = d._size;195}196uint i;197for( i=0; i<_size; i++ ) // All buckets are empty198_bin[i]._cnt = 0; // But leave bucket allocations alone199_cnt = d._cnt;200*(Hash*)(&_hash) = d._hash;201*(CmpKey*)(&_cmp) = d._cmp;202for( i=0; i<_size; i++ ) {203bucket *b = &d._bin[i]; // Shortcut to source bucket204for( uint j=0; j<b->_cnt; j++ )205Insert( b->_keyvals[j+j], b->_keyvals[j+j+1] );206}207return *this;208}209210//------------------------------Insert----------------------------------------211// Insert or replace a key/value pair in the given dictionary. If the212// dictionary is too full, it's size is doubled. The prior value being213// replaced is returned (NULL if this is a 1st insertion of that key). If214// an old value is found, it's swapped with the prior key-value pair on the215// list. This moves a commonly searched-for value towards the list head.216void *Dict::Insert(void *key, void *val, bool replace) {217uint hash = _hash( key ); // Get hash key218uint i = hash & (_size-1); // Get hash key, corrected for size219bucket *b = &_bin[i]; // Handy shortcut220for( uint j=0; j<b->_cnt; j++ ) {221if( !_cmp(key,b->_keyvals[j+j]) ) {222if (!replace) {223return b->_keyvals[j+j+1];224} else {225void *prior = b->_keyvals[j+j+1];226b->_keyvals[j+j ] = key; // Insert current key-value227b->_keyvals[j+j+1] = val;228return prior; // Return prior229}230}231}232if( ++_cnt > _size ) { // Hash table is full233doubhash(); // Grow whole table if too full234i = hash & (_size-1); // Rehash235b = &_bin[i]; // Handy shortcut236}237if( b->_cnt == b->_max ) { // Must grow bucket?238if( !b->_keyvals ) {239b->_max = 2; // Initial bucket size240b->_keyvals = (void**)_arena->Amalloc_4(sizeof(void*) * b->_max * 2);241} else {242b->_keyvals = (void**)_arena->Arealloc(b->_keyvals, sizeof(void*) * b->_max * 2, sizeof(void*) * b->_max * 4);243b->_max <<= 1; // Double bucket244}245}246b->_keyvals[b->_cnt+b->_cnt ] = key;247b->_keyvals[b->_cnt+b->_cnt+1] = val;248b->_cnt++;249return NULL; // Nothing found prior250}251252//------------------------------Delete---------------------------------------253// Find & remove a value from dictionary. Return old value.254void *Dict::Delete(void *key) {255uint i = _hash( key ) & (_size-1); // Get hash key, corrected for size256bucket *b = &_bin[i]; // Handy shortcut257for( uint j=0; j<b->_cnt; j++ )258if( !_cmp(key,b->_keyvals[j+j]) ) {259void *prior = b->_keyvals[j+j+1];260b->_cnt--; // Remove key/value from lo bucket261b->_keyvals[j+j ] = b->_keyvals[b->_cnt+b->_cnt ];262b->_keyvals[j+j+1] = b->_keyvals[b->_cnt+b->_cnt+1];263_cnt--; // One less thing in table264return prior;265}266return NULL;267}268269//------------------------------FindDict-------------------------------------270// Find a key-value pair in the given dictionary. If not found, return NULL.271// If found, move key-value pair towards head of list.272void *Dict::operator [](const void *key) const {273uint i = _hash( key ) & (_size-1); // Get hash key, corrected for size274bucket *b = &_bin[i]; // Handy shortcut275for( uint j=0; j<b->_cnt; j++ )276if( !_cmp(key,b->_keyvals[j+j]) )277return b->_keyvals[j+j+1];278return NULL;279}280281//------------------------------CmpDict--------------------------------------282// CmpDict compares two dictionaries; they must have the same keys (their283// keys must match using CmpKey) and they must have the same values (pointer284// comparison). If so 1 is returned, if not 0 is returned.285int32 Dict::operator ==(const Dict &d2) const {286if( _cnt != d2._cnt ) return 0;287if( _hash != d2._hash ) return 0;288if( _cmp != d2._cmp ) return 0;289for( uint i=0; i < _size; i++) { // For complete hash table do290bucket *b = &_bin[i]; // Handy shortcut291if( b->_cnt != d2._bin[i]._cnt ) return 0;292if( memcmp(b->_keyvals, d2._bin[i]._keyvals, b->_cnt*2*sizeof(void*) ) )293return 0; // Key-value pairs must match294}295return 1; // All match, is OK296}297298//------------------------------print------------------------------------------299// Handier print routine300void Dict::print() {301DictI i(this); // Moved definition in iterator here because of g++.302tty->print("Dict@0x%lx[%d] = {", this, _cnt);303for( ; i.test(); ++i ) {304tty->print("(0x%lx,0x%lx),", i._key, i._value);305}306tty->print_cr("}");307}308309//------------------------------Hashing Functions----------------------------310// Convert string to hash key. This algorithm implements a universal hash311// function with the multipliers frozen (ok, so it's not universal). The312// multipliers (and allowable characters) are all odd, so the resultant sum313// is odd - guaranteed not divisible by any power of two, so the hash tables314// can be any power of two with good results. Also, I choose multipliers315// that have only 2 bits set (the low is always set to be odd) so316// multiplication requires only shifts and adds. Characters are required to317// be in the range 0-127 (I double & add 1 to force oddness). Keys are318// limited to MAXID characters in length. Experimental evidence on 150K of319// C text shows excellent spreading of values for any size hash table.320int hashstr(const void *t) {321register char c, k = 0;322register int32 sum = 0;323register const char *s = (const char *)t;324325while( ((c = *s++) != '\0') && (k < MAXID-1) ) { // Get characters till null or MAXID-1326c = (c<<1)+1; // Characters are always odd!327sum += c + (c<<shft[k++]); // Universal hash function328}329return (int)((sum+xsum[k]) >> 1); // Hash key, un-modulo'd table size330}331332//------------------------------hashptr--------------------------------------333// Slimey cheap hash function; no guaranteed performance. Better than the334// default for pointers, especially on MS-DOS machines.335int hashptr(const void *key) {336#ifdef __TURBOC__337return ((intptr_t)key >> 16);338#else // __TURBOC__339return ((intptr_t)key >> 2);340#endif341}342343// Slimey cheap hash function; no guaranteed performance.344int hashkey(const void *key) {345return (intptr_t)key;346}347348//------------------------------Key Comparator Functions---------------------349int32 cmpstr(const void *k1, const void *k2) {350return strcmp((const char *)k1,(const char *)k2);351}352353// Cheap key comparator.354int32 cmpkey(const void *key1, const void *key2) {355if (key1 == key2) return 0;356intptr_t delta = (intptr_t)key1 - (intptr_t)key2;357if (delta > 0) return 1;358return -1;359}360361//=============================================================================362//------------------------------reset------------------------------------------363// Create an iterator and initialize the first variables.364void DictI::reset( const Dict *dict ) {365_d = dict; // The dictionary366_i = (uint)-1; // Before the first bin367_j = 0; // Nothing left in the current bin368++(*this); // Step to first real value369}370371//------------------------------next-------------------------------------------372// Find the next key-value pair in the dictionary, or return a NULL key and373// value.374void DictI::operator ++(void) {375if( _j-- ) { // Still working in current bin?376_key = _d->_bin[_i]._keyvals[_j+_j];377_value = _d->_bin[_i]._keyvals[_j+_j+1];378return;379}380381while( ++_i < _d->_size ) { // Else scan for non-zero bucket382_j = _d->_bin[_i]._cnt;383if( !_j ) continue;384_j--;385_key = _d->_bin[_i]._keyvals[_j+_j];386_value = _d->_bin[_i]._keyvals[_j+_j+1];387return;388}389_key = _value = NULL;390}391392393