1 /*
   2  * Copyright (c) 1999, 2012, 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 "c1/c1_Canonicalizer.hpp"
  27 #include "c1/c1_IR.hpp"
  28 #include "c1/c1_ValueMap.hpp"
  29 #include "utilities/bitMap.inline.hpp"
  30 
  31 
  32 #ifndef PRODUCT
  33 
  34   int ValueMap::_number_of_finds = 0;
  35   int ValueMap::_number_of_hits = 0;
  36   int ValueMap::_number_of_kills = 0;
  37 
  38   #define TRACE_VALUE_NUMBERING(code) if (PrintValueNumbering) { code; }
  39 
  40 #else
  41 
  42   #define TRACE_VALUE_NUMBERING(code)
  43 
  44 #endif
  45 
  46 
  47 ValueMap::ValueMap()
  48   : _nesting(0)
  49   , _entries(ValueMapInitialSize, NULL)
  50   , _killed_values()
  51   , _entry_count(0)
  52 {
  53   NOT_PRODUCT(reset_statistics());
  54 }
  55 
  56 
  57 ValueMap::ValueMap(ValueMap* old)
  58   : _nesting(old->_nesting + 1)
  59   , _entries(old->_entries.length())
  60   , _killed_values()
  61   , _entry_count(old->_entry_count)
  62 {
  63   for (int i = size() - 1; i >= 0; i--) {
  64     _entries.at_put(i, old->entry_at(i));
  65   }
  66   _killed_values.set_from(&old->_killed_values);
  67 }
  68 
  69 
  70 void ValueMap::increase_table_size() {
  71   int old_size = size();
  72   int new_size = old_size * 2 + 1;
  73 
  74   ValueMapEntryList worklist(8);
  75   ValueMapEntryArray new_entries(new_size, NULL);
  76   int new_entry_count = 0;
  77 
  78   TRACE_VALUE_NUMBERING(tty->print_cr("increasing table size from %d to %d", old_size, new_size));
  79 
  80   for (int i = old_size - 1; i >= 0; i--) {
  81     ValueMapEntry* entry;
  82     for (entry = entry_at(i); entry != NULL; entry = entry->next()) {
  83       if (!is_killed(entry->value())) {
  84         worklist.push(entry);
  85       }
  86     }
  87 
  88     while (!worklist.is_empty()) {
  89       entry = worklist.pop();
  90       int new_index = entry_index(entry->hash(), new_size);
  91 
  92       if (entry->nesting() != nesting() && new_entries.at(new_index) != entry->next()) {
  93         // changing entries with a lower nesting than the current nesting of the table
  94         // is not allowed because then the same entry is contained in multiple value maps.
  95         // clone entry when next-pointer must be changed
  96         entry = new ValueMapEntry(entry->hash(), entry->value(), entry->nesting(), NULL);
  97       }
  98       entry->set_next(new_entries.at(new_index));
  99       new_entries.at_put(new_index, entry);
 100       new_entry_count++;
 101     }
 102   }
 103 
 104   _entries = new_entries;
 105   _entry_count = new_entry_count;
 106 }
 107 
 108 
 109 Value ValueMap::find_insert(Value x) {
 110   const intx hash = x->hash();
 111   if (hash != 0) {
 112     // 0 hash means: exclude from value numbering
 113     NOT_PRODUCT(_number_of_finds++);
 114 
 115     for (ValueMapEntry* entry = entry_at(entry_index(hash, size())); entry != NULL; entry = entry->next()) {
 116       if (entry->hash() == hash) {
 117         Value f = entry->value();
 118 
 119         if (!is_killed(f) && f->is_equal(x)) {
 120           NOT_PRODUCT(_number_of_hits++);
 121           TRACE_VALUE_NUMBERING(tty->print_cr("Value Numbering: %s %c%d equal to %c%d  (size %d, entries %d, nesting-diff %d)", x->name(), x->type()->tchar(), x->id(), f->type()->tchar(), f->id(), size(), entry_count(), nesting() - entry->nesting()));
 122 
 123           if (entry->nesting() != nesting() && f->as_Constant() == NULL) {
 124             // non-constant values of of another block must be pinned,
 125             // otherwise it is possible that they are not evaluated
 126             f->pin(Instruction::PinGlobalValueNumbering);
 127           }
 128           assert(x->type()->tag() == f->type()->tag(), "should have same type");
 129 
 130           return f;
 131 
 132         }
 133       }
 134     }
 135 
 136     // x not found, so insert it
 137     if (entry_count() >= size_threshold()) {
 138       increase_table_size();
 139     }
 140     int idx = entry_index(hash, size());
 141     _entries.at_put(idx, new ValueMapEntry(hash, x, nesting(), entry_at(idx)));
 142     _entry_count++;
 143 
 144     TRACE_VALUE_NUMBERING(tty->print_cr("Value Numbering: insert %s %c%d  (size %d, entries %d, nesting %d)", x->name(), x->type()->tchar(), x->id(), size(), entry_count(), nesting()));
 145   }
 146 
 147   return x;
 148 }
 149 
 150 
 151 #define GENERIC_KILL_VALUE(must_kill_implementation)                                     \
 152   NOT_PRODUCT(_number_of_kills++);                                                       \
 153                                                                                          \
 154   for (int i = size() - 1; i >= 0; i--) {                                                \
 155     ValueMapEntry* prev_entry = NULL;                                                    \
 156     for (ValueMapEntry* entry = entry_at(i); entry != NULL; entry = entry->next()) {     \
 157       Value value = entry->value();                                                      \
 158                                                                                          \
 159       must_kill_implementation(must_kill, entry, value)                                  \
 160                                                                                          \
 161       if (must_kill) {                                                                   \
 162         kill_value(value);                                                               \
 163                                                                                          \
 164         if (prev_entry == NULL) {                                                        \
 165           _entries.at_put(i, entry->next());                                             \
 166           _entry_count--;                                                                \
 167         } else if (prev_entry->nesting() == nesting()) {                                 \
 168           prev_entry->set_next(entry->next());                                           \
 169           _entry_count--;                                                                \
 170         } else {                                                                         \
 171           prev_entry = entry;                                                            \
 172         }                                                                                \
 173                                                                                          \
 174         TRACE_VALUE_NUMBERING(tty->print_cr("Value Numbering: killed %s %c%d  (size %d, entries %d, nesting-diff %d)", value->name(), value->type()->tchar(), value->id(), size(), entry_count(), nesting() - entry->nesting()));   \
 175       } else {                                                                           \
 176         prev_entry = entry;                                                              \
 177       }                                                                                  \
 178     }                                                                                    \
 179   }                                                                                      \
 180 
 181 #define MUST_KILL_MEMORY(must_kill, entry, value)                                        \
 182   bool must_kill = value->as_LoadField() != NULL || value->as_LoadIndexed() != NULL;
 183 
 184 #define MUST_KILL_ARRAY(must_kill, entry, value)                                         \
 185   bool must_kill = value->as_LoadIndexed() != NULL                                       \
 186                    && value->type()->tag() == type->tag();
 187 
 188 #define MUST_KILL_FIELD(must_kill, entry, value)                                         \
 189   /* ciField's are not unique; must compare their contents */                            \
 190   LoadField* lf = value->as_LoadField();                                                 \
 191   bool must_kill = lf != NULL                                                            \
 192                    && lf->field()->holder() == field->holder()                           \
 193                    && (all_offsets || lf->field()->offset() == field->offset());
 194 
 195 #define MUST_KILL_EXCEPTION(must_kill, entry, value)                                     \
 196   assert(entry->nesting() < nesting(), "must not find bigger nesting than current");     \
 197   bool must_kill = (entry->nesting() == nesting() - 1);
 198 
 199 
 200 void ValueMap::kill_memory() {
 201   GENERIC_KILL_VALUE(MUST_KILL_MEMORY);
 202 }
 203 
 204 void ValueMap::kill_array(ValueType* type) {
 205   GENERIC_KILL_VALUE(MUST_KILL_ARRAY);
 206 }
 207 
 208 void ValueMap::kill_field(ciField* field, bool all_offsets) {
 209   GENERIC_KILL_VALUE(MUST_KILL_FIELD);
 210 }
 211 
 212 void ValueMap::kill_exception() {
 213   GENERIC_KILL_VALUE(MUST_KILL_EXCEPTION);
 214 }
 215 
 216 
 217 void ValueMap::kill_map(ValueMap* map) {
 218   assert(is_global_value_numbering(), "only for global value numbering");
 219   _killed_values.set_union(&map->_killed_values);
 220 }
 221 
 222 void ValueMap::kill_all() {
 223   assert(is_local_value_numbering(), "only for local value numbering");
 224   for (int i = size() - 1; i >= 0; i--) {
 225     _entries.at_put(i, NULL);
 226   }
 227   _entry_count = 0;
 228 }
 229 
 230 
 231 #ifndef PRODUCT
 232 
 233 void ValueMap::print() {
 234   tty->print_cr("(size %d, entries %d, nesting %d)", size(), entry_count(), nesting());
 235 
 236   int entries = 0;
 237   for (int i = 0; i < size(); i++) {
 238     if (entry_at(i) != NULL) {
 239       tty->print("  %2d: ", i);
 240       for (ValueMapEntry* entry = entry_at(i); entry != NULL; entry = entry->next()) {
 241         Value value = entry->value();
 242         tty->print("%s %c%d (%s%d) -> ", value->name(), value->type()->tchar(), value->id(), is_killed(value) ? "x" : "", entry->nesting());
 243         entries++;
 244       }
 245       tty->print_cr("NULL");
 246     }
 247   }
 248 
 249   _killed_values.print();
 250   assert(entry_count() == entries, "entry_count incorrect");
 251 }
 252 
 253 void ValueMap::reset_statistics() {
 254   _number_of_finds = 0;
 255   _number_of_hits = 0;
 256   _number_of_kills = 0;
 257 }
 258 
 259 void ValueMap::print_statistics() {
 260   float hit_rate = 0;
 261   if (_number_of_finds != 0) {
 262     hit_rate = (float)_number_of_hits / _number_of_finds;
 263   }
 264 
 265   tty->print_cr("finds:%3d  hits:%3d   kills:%3d  hit rate: %1.4f", _number_of_finds, _number_of_hits, _number_of_kills, hit_rate);
 266 }
 267 
 268 #endif
 269 
 270 
 271 
 272 class ShortLoopOptimizer : public ValueNumberingVisitor {
 273  private:
 274   GlobalValueNumbering* _gvn;
 275   BlockList             _loop_blocks;
 276   bool                  _too_complicated_loop;
 277 
 278   // simplified access to methods of GlobalValueNumbering
 279   ValueMap* current_map()                        { return _gvn->current_map(); }
 280   ValueMap* value_map_of(BlockBegin* block)      { return _gvn->value_map_of(block); }
 281 
 282   // implementation for abstract methods of ValueNumberingVisitor
 283   void      kill_memory()                                 { _too_complicated_loop = true; }
 284   void      kill_field(ciField* field, bool all_offsets)  { current_map()->kill_field(field, all_offsets); };
 285   void      kill_array(ValueType* type)                   { current_map()->kill_array(type); };
 286 
 287  public:
 288   ShortLoopOptimizer(GlobalValueNumbering* gvn)
 289     : _gvn(gvn)
 290     , _loop_blocks(ValueMapMaxLoopSize)
 291     , _too_complicated_loop(false)
 292   {
 293   }
 294 
 295   bool process(BlockBegin* loop_header);
 296 };
 297 
 298 
 299 bool ShortLoopOptimizer::process(BlockBegin* loop_header) {
 300   TRACE_VALUE_NUMBERING(tty->print_cr("** loop header block"));
 301 
 302   _too_complicated_loop = false;
 303   _loop_blocks.clear();
 304   _loop_blocks.append(loop_header);
 305 
 306   for (int i = 0; i < _loop_blocks.length(); i++) {
 307     BlockBegin* block = _loop_blocks.at(i);
 308     TRACE_VALUE_NUMBERING(tty->print_cr("processing loop block B%d", block->block_id()));
 309 
 310     if (block->is_set(BlockBegin::exception_entry_flag)) {
 311       // this would be too complicated
 312       return false;
 313     }
 314 
 315     // add predecessors to worklist
 316     for (int j = block->number_of_preds() - 1; j >= 0; j--) {
 317       BlockBegin* pred = block->pred_at(j);
 318 
 319       ValueMap* pred_map = value_map_of(pred);
 320       if (pred_map != NULL) {
 321         current_map()->kill_map(pred_map);
 322       } else if (!_loop_blocks.contains(pred)) {
 323         if (_loop_blocks.length() >= ValueMapMaxLoopSize) {
 324           return false;
 325         }
 326         _loop_blocks.append(pred);
 327       }
 328     }
 329 
 330     // use the instruction visitor for killing values
 331     for (Value instr = block->next(); instr != NULL; instr = instr->next()) {
 332       instr->visit(this);
 333       if (_too_complicated_loop) {
 334         return false;
 335       }
 336     }
 337   }
 338 
 339   TRACE_VALUE_NUMBERING(tty->print_cr("** loop successfully optimized"));
 340   return true;
 341 }
 342 
 343 
 344 GlobalValueNumbering::GlobalValueNumbering(IR* ir)
 345   : _current_map(NULL)
 346   , _value_maps(ir->linear_scan_order()->length(), NULL)
 347 {
 348   TRACE_VALUE_NUMBERING(tty->print_cr("****** start of global value numbering"));
 349 
 350   ShortLoopOptimizer short_loop_optimizer(this);
 351   int subst_count = 0;
 352 
 353   BlockList* blocks = ir->linear_scan_order();
 354   int num_blocks = blocks->length();
 355 
 356   BlockBegin* start_block = blocks->at(0);
 357   assert(start_block == ir->start() && start_block->number_of_preds() == 0 && start_block->dominator() == NULL, "must be start block");
 358   assert(start_block->next()->as_Base() != NULL && start_block->next()->next() == NULL, "start block must not have instructions");
 359 
 360   // initial, empty value map with nesting 0
 361   set_value_map_of(start_block, new ValueMap());
 362 
 363   for (int i = 1; i < num_blocks; i++) {
 364     BlockBegin* block = blocks->at(i);
 365     TRACE_VALUE_NUMBERING(tty->print_cr("**** processing block B%d", block->block_id()));
 366 
 367     int num_preds = block->number_of_preds();
 368     assert(num_preds > 0, "block must have predecessors");
 369 
 370     BlockBegin* dominator = block->dominator();
 371     assert(dominator != NULL, "dominator must exist");
 372     assert(value_map_of(dominator) != NULL, "value map of dominator must exist");
 373 
 374     // create new value map with increased nesting
 375     _current_map = new ValueMap(value_map_of(dominator));
 376 
 377     if (num_preds == 1) {
 378       assert(dominator == block->pred_at(0), "dominator must be equal to predecessor");
 379       // nothing to do here
 380 
 381     } else if (block->is_set(BlockBegin::linear_scan_loop_header_flag)) {
 382       // block has incoming backward branches -> try to optimize short loops
 383       if (!short_loop_optimizer.process(block)) {
 384         // loop is too complicated, so kill all memory loads because there might be
 385         // stores to them in the loop
 386         current_map()->kill_memory();
 387       }
 388 
 389     } else {
 390       // only incoming forward branches that are already processed
 391       for (int j = 0; j < num_preds; j++) {
 392         BlockBegin* pred = block->pred_at(j);
 393         ValueMap* pred_map = value_map_of(pred);
 394 
 395         if (pred_map != NULL) {
 396           // propagate killed values of the predecessor to this block
 397           current_map()->kill_map(value_map_of(pred));
 398         } else {
 399           // kill all memory loads because predecessor not yet processed
 400           // (this can happen with non-natural loops and OSR-compiles)
 401           current_map()->kill_memory();
 402         }
 403       }
 404     }
 405 
 406     if (block->is_set(BlockBegin::exception_entry_flag)) {
 407       current_map()->kill_exception();
 408     }
 409 
 410     TRACE_VALUE_NUMBERING(tty->print("value map before processing block: "); current_map()->print());
 411 
 412     // visit all instructions of this block
 413     for (Value instr = block->next(); instr != NULL; instr = instr->next()) {
 414       assert(!instr->has_subst(), "substitution already set");
 415 
 416       // check if instruction kills any values
 417       instr->visit(this);
 418 
 419       if (instr->hash() != 0) {
 420         Value f = current_map()->find_insert(instr);
 421         if (f != instr) {
 422           assert(!f->has_subst(), "can't have a substitution");
 423           instr->set_subst(f);
 424           subst_count++;
 425         }
 426       }
 427     }
 428 
 429     // remember value map for successors
 430     set_value_map_of(block, current_map());
 431   }
 432 
 433   if (subst_count != 0) {
 434     SubstitutionResolver resolver(ir);
 435   }
 436 
 437   TRACE_VALUE_NUMBERING(tty->print("****** end of global value numbering. "); ValueMap::print_statistics());
 438 }