1 /*
   2  * Copyright (c) 2007, 2013, 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 #include "precompiled.hpp"
  25 #include "compiler/compileLog.hpp"
  26 #include "libadt/vectset.hpp"
  27 #include "memory/allocation.inline.hpp"
  28 #include "opto/addnode.hpp"
  29 #include "opto/callnode.hpp"
  30 #include "opto/divnode.hpp"
  31 #include "opto/matcher.hpp"
  32 #include "opto/memnode.hpp"
  33 #include "opto/mulnode.hpp"
  34 #include "opto/opcodes.hpp"
  35 #include "opto/superword.hpp"
  36 #include "opto/vectornode.hpp"
  37 
  38 //
  39 //                  S U P E R W O R D   T R A N S F O R M
  40 //=============================================================================
  41 
  42 //------------------------------SuperWord---------------------------
  43 SuperWord::SuperWord(PhaseIdealLoop* phase) :
  44   _phase(phase),
  45   _igvn(phase->_igvn),
  46   _arena(phase->C->comp_arena()),
  47   _packset(arena(), 8,  0, NULL),         // packs for the current block
  48   _bb_idx(arena(), (int)(1.10 * phase->C->unique()), 0, 0), // node idx to index in bb
  49   _block(arena(), 8,  0, NULL),           // nodes in current block
  50   _data_entry(arena(), 8,  0, NULL),      // nodes with all inputs from outside
  51   _mem_slice_head(arena(), 8,  0, NULL),  // memory slice heads
  52   _mem_slice_tail(arena(), 8,  0, NULL),  // memory slice tails
  53   _node_info(arena(), 8,  0, SWNodeInfo::initial), // info needed per node
  54   _align_to_ref(NULL),                    // memory reference to align vectors to
  55   _disjoint_ptrs(arena(), 8,  0, OrderedPair::initial), // runtime disambiguated pointer pairs
  56   _dg(_arena),                            // dependence graph
  57   _visited(arena()),                      // visited node set
  58   _post_visited(arena()),                 // post visited node set
  59   _n_idx_list(arena(), 8),                // scratch list of (node,index) pairs
  60   _stk(arena(), 8, 0, NULL),              // scratch stack of nodes
  61   _nlist(arena(), 8, 0, NULL),            // scratch list of nodes
  62   _lpt(NULL),                             // loop tree node
  63   _lp(NULL),                              // LoopNode
  64   _bb(NULL),                              // basic block
  65   _iv(NULL)                               // induction var
  66 {}
  67 
  68 //------------------------------transform_loop---------------------------
  69 void SuperWord::transform_loop(IdealLoopTree* lpt) {
  70   assert(UseSuperWord, "should be");
  71   // Do vectors exist on this architecture?
  72   if (Matcher::vector_width_in_bytes(T_BYTE) < 2) return;
  73 
  74   assert(lpt->_head->is_CountedLoop(), "must be");
  75   CountedLoopNode *cl = lpt->_head->as_CountedLoop();
  76 
  77   if (!cl->is_valid_counted_loop()) return; // skip malformed counted loop
  78 
  79   if (!cl->is_main_loop() ) return; // skip normal, pre, and post loops
  80 
  81   // Check for no control flow in body (other than exit)
  82   Node *cl_exit = cl->loopexit();
  83   if (cl_exit->in(0) != lpt->_head) return;
  84 
  85   // Make sure the are no extra control users of the loop backedge
  86   if (cl->back_control()->outcnt() != 1) {
  87     return;
  88   }
  89 
  90   // Check for pre-loop ending with CountedLoopEnd(Bool(Cmp(x,Opaque1(limit))))
  91   CountedLoopEndNode* pre_end = get_pre_loop_end(cl);
  92   if (pre_end == NULL) return;
  93   Node *pre_opaq1 = pre_end->limit();
  94   if (pre_opaq1->Opcode() != Op_Opaque1) return;
  95 
  96   init(); // initialize data structures
  97 
  98   set_lpt(lpt);
  99   set_lp(cl);
 100 
 101   // For now, define one block which is the entire loop body
 102   set_bb(cl);
 103 
 104   assert(_packset.length() == 0, "packset must be empty");
 105   SLP_extract();
 106 }
 107 
 108 //------------------------------SLP_extract---------------------------
 109 // Extract the superword level parallelism
 110 //
 111 // 1) A reverse post-order of nodes in the block is constructed.  By scanning
 112 //    this list from first to last, all definitions are visited before their uses.
 113 //
 114 // 2) A point-to-point dependence graph is constructed between memory references.
 115 //    This simplies the upcoming "independence" checker.
 116 //
 117 // 3) The maximum depth in the node graph from the beginning of the block
 118 //    to each node is computed.  This is used to prune the graph search
 119 //    in the independence checker.
 120 //
 121 // 4) For integer types, the necessary bit width is propagated backwards
 122 //    from stores to allow packed operations on byte, char, and short
 123 //    integers.  This reverses the promotion to type "int" that javac
 124 //    did for operations like: char c1,c2,c3;  c1 = c2 + c3.
 125 //
 126 // 5) One of the memory references is picked to be an aligned vector reference.
 127 //    The pre-loop trip count is adjusted to align this reference in the
 128 //    unrolled body.
 129 //
 130 // 6) The initial set of pack pairs is seeded with memory references.
 131 //
 132 // 7) The set of pack pairs is extended by following use->def and def->use links.
 133 //
 134 // 8) The pairs are combined into vector sized packs.
 135 //
 136 // 9) Reorder the memory slices to co-locate members of the memory packs.
 137 //
 138 // 10) Generate ideal vector nodes for the final set of packs and where necessary,
 139 //    inserting scalar promotion, vector creation from multiple scalars, and
 140 //    extraction of scalar values from vectors.
 141 //
 142 void SuperWord::SLP_extract() {
 143 
 144   // Ready the block
 145 
 146   if (!construct_bb())
 147     return; // Exit if no interesting nodes or complex graph.
 148 
 149   dependence_graph();
 150 
 151   compute_max_depth();
 152 
 153   compute_vector_element_type();
 154 
 155   // Attempt vectorization
 156 
 157   find_adjacent_refs();
 158 
 159   extend_packlist();
 160 
 161   combine_packs();
 162 
 163   construct_my_pack_map();
 164 
 165   filter_packs();
 166 
 167   schedule();
 168 
 169   output();
 170 }
 171 
 172 //------------------------------find_adjacent_refs---------------------------
 173 // Find the adjacent memory references and create pack pairs for them.
 174 // This is the initial set of packs that will then be extended by
 175 // following use->def and def->use links.  The align positions are
 176 // assigned relative to the reference "align_to_ref"
 177 void SuperWord::find_adjacent_refs() {
 178   // Get list of memory operations
 179   Node_List memops;
 180   for (int i = 0; i < _block.length(); i++) {
 181     Node* n = _block.at(i);
 182     if (n->is_Mem() && !n->is_LoadStore() && in_bb(n) &&
 183         is_java_primitive(n->as_Mem()->memory_type())) {
 184       int align = memory_alignment(n->as_Mem(), 0);
 185       if (align != bottom_align) {
 186         memops.push(n);
 187       }
 188     }
 189   }
 190 
 191   Node_List align_to_refs;
 192   int best_iv_adjustment = 0;
 193   MemNode* best_align_to_mem_ref = NULL;
 194 
 195   while (memops.size() != 0) {
 196     // Find a memory reference to align to.
 197     MemNode* mem_ref = find_align_to_ref(memops);
 198     if (mem_ref == NULL) break;
 199     align_to_refs.push(mem_ref);
 200     int iv_adjustment = get_iv_adjustment(mem_ref);
 201 
 202     if (best_align_to_mem_ref == NULL) {
 203       // Set memory reference which is the best from all memory operations
 204       // to be used for alignment. The pre-loop trip count is modified to align
 205       // this reference to a vector-aligned address.
 206       best_align_to_mem_ref = mem_ref;
 207       best_iv_adjustment = iv_adjustment;
 208     }
 209 
 210     SWPointer align_to_ref_p(mem_ref, this);
 211     // Set alignment relative to "align_to_ref" for all related memory operations.
 212     for (int i = memops.size() - 1; i >= 0; i--) {
 213       MemNode* s = memops.at(i)->as_Mem();
 214       if (isomorphic(s, mem_ref)) {
 215         SWPointer p2(s, this);
 216         if (p2.comparable(align_to_ref_p)) {
 217           int align = memory_alignment(s, iv_adjustment);
 218           set_alignment(s, align);
 219         }
 220       }
 221     }
 222 
 223     // Create initial pack pairs of memory operations for which
 224     // alignment is set and vectors will be aligned.
 225     bool create_pack = true;
 226     if (memory_alignment(mem_ref, best_iv_adjustment) == 0) {
 227       if (!Matcher::misaligned_vectors_ok()) {
 228         int vw = vector_width(mem_ref);
 229         int vw_best = vector_width(best_align_to_mem_ref);
 230         if (vw > vw_best) {
 231           // Do not vectorize a memory access with more elements per vector
 232           // if unaligned memory access is not allowed because number of
 233           // iterations in pre-loop will be not enough to align it.
 234           create_pack = false;
 235         }
 236       }
 237     } else {
 238       if (same_velt_type(mem_ref, best_align_to_mem_ref)) {
 239         // Can't allow vectorization of unaligned memory accesses with the
 240         // same type since it could be overlapped accesses to the same array.
 241         create_pack = false;
 242       } else {
 243         // Allow independent (different type) unaligned memory operations
 244         // if HW supports them.
 245         if (!Matcher::misaligned_vectors_ok()) {
 246           create_pack = false;
 247         } else {
 248           // Check if packs of the same memory type but
 249           // with a different alignment were created before.
 250           for (uint i = 0; i < align_to_refs.size(); i++) {
 251             MemNode* mr = align_to_refs.at(i)->as_Mem();
 252             if (same_velt_type(mr, mem_ref) &&
 253                 memory_alignment(mr, iv_adjustment) != 0)
 254               create_pack = false;
 255           }
 256         }
 257       }
 258     }
 259     if (create_pack) {
 260       for (uint i = 0; i < memops.size(); i++) {
 261         Node* s1 = memops.at(i);
 262         int align = alignment(s1);
 263         if (align == top_align) continue;
 264         for (uint j = 0; j < memops.size(); j++) {
 265           Node* s2 = memops.at(j);
 266           if (alignment(s2) == top_align) continue;
 267           if (s1 != s2 && are_adjacent_refs(s1, s2)) {
 268             if (stmts_can_pack(s1, s2, align)) {
 269               Node_List* pair = new Node_List();
 270               pair->push(s1);
 271               pair->push(s2);
 272               _packset.append(pair);
 273             }
 274           }
 275         }
 276       }
 277     } else { // Don't create unaligned pack
 278       // First, remove remaining memory ops of the same type from the list.
 279       for (int i = memops.size() - 1; i >= 0; i--) {
 280         MemNode* s = memops.at(i)->as_Mem();
 281         if (same_velt_type(s, mem_ref)) {
 282           memops.remove(i);
 283         }
 284       }
 285 
 286       // Second, remove already constructed packs of the same type.
 287       for (int i = _packset.length() - 1; i >= 0; i--) {
 288         Node_List* p = _packset.at(i);
 289         MemNode* s = p->at(0)->as_Mem();
 290         if (same_velt_type(s, mem_ref)) {
 291           remove_pack_at(i);
 292         }
 293       }
 294 
 295       // If needed find the best memory reference for loop alignment again.
 296       if (same_velt_type(mem_ref, best_align_to_mem_ref)) {
 297         // Put memory ops from remaining packs back on memops list for
 298         // the best alignment search.
 299         uint orig_msize = memops.size();
 300         for (int i = 0; i < _packset.length(); i++) {
 301           Node_List* p = _packset.at(i);
 302           MemNode* s = p->at(0)->as_Mem();
 303           assert(!same_velt_type(s, mem_ref), "sanity");
 304           memops.push(s);
 305         }
 306         MemNode* best_align_to_mem_ref = find_align_to_ref(memops);
 307         if (best_align_to_mem_ref == NULL) break;
 308         best_iv_adjustment = get_iv_adjustment(best_align_to_mem_ref);
 309         // Restore list.
 310         while (memops.size() > orig_msize)
 311           (void)memops.pop();
 312       }
 313     } // unaligned memory accesses
 314 
 315     // Remove used mem nodes.
 316     for (int i = memops.size() - 1; i >= 0; i--) {
 317       MemNode* m = memops.at(i)->as_Mem();
 318       if (alignment(m) != top_align) {
 319         memops.remove(i);
 320       }
 321     }
 322 
 323   } // while (memops.size() != 0
 324   set_align_to_ref(best_align_to_mem_ref);
 325 
 326 #ifndef PRODUCT
 327   if (TraceSuperWord) {
 328     tty->print_cr("\nAfter find_adjacent_refs");
 329     print_packset();
 330   }
 331 #endif
 332 }
 333 
 334 //------------------------------find_align_to_ref---------------------------
 335 // Find a memory reference to align the loop induction variable to.
 336 // Looks first at stores then at loads, looking for a memory reference
 337 // with the largest number of references similar to it.
 338 MemNode* SuperWord::find_align_to_ref(Node_List &memops) {
 339   GrowableArray<int> cmp_ct(arena(), memops.size(), memops.size(), 0);
 340 
 341   // Count number of comparable memory ops
 342   for (uint i = 0; i < memops.size(); i++) {
 343     MemNode* s1 = memops.at(i)->as_Mem();
 344     SWPointer p1(s1, this);
 345     // Discard if pre loop can't align this reference
 346     if (!ref_is_alignable(p1)) {
 347       *cmp_ct.adr_at(i) = 0;
 348       continue;
 349     }
 350     for (uint j = i+1; j < memops.size(); j++) {
 351       MemNode* s2 = memops.at(j)->as_Mem();
 352       if (isomorphic(s1, s2)) {
 353         SWPointer p2(s2, this);
 354         if (p1.comparable(p2)) {
 355           (*cmp_ct.adr_at(i))++;
 356           (*cmp_ct.adr_at(j))++;
 357         }
 358       }
 359     }
 360   }
 361 
 362   // Find Store (or Load) with the greatest number of "comparable" references,
 363   // biggest vector size, smallest data size and smallest iv offset.
 364   int max_ct        = 0;
 365   int max_vw        = 0;
 366   int max_idx       = -1;
 367   int min_size      = max_jint;
 368   int min_iv_offset = max_jint;
 369   for (uint j = 0; j < memops.size(); j++) {
 370     MemNode* s = memops.at(j)->as_Mem();
 371     if (s->is_Store()) {
 372       int vw = vector_width_in_bytes(s);
 373       assert(vw > 1, "sanity");
 374       SWPointer p(s, this);
 375       if (cmp_ct.at(j) >  max_ct ||
 376           cmp_ct.at(j) == max_ct &&
 377             (vw >  max_vw ||
 378              vw == max_vw &&
 379               (data_size(s) <  min_size ||
 380                data_size(s) == min_size &&
 381                  (p.offset_in_bytes() < min_iv_offset)))) {
 382         max_ct = cmp_ct.at(j);
 383         max_vw = vw;
 384         max_idx = j;
 385         min_size = data_size(s);
 386         min_iv_offset = p.offset_in_bytes();
 387       }
 388     }
 389   }
 390   // If no stores, look at loads
 391   if (max_ct == 0) {
 392     for (uint j = 0; j < memops.size(); j++) {
 393       MemNode* s = memops.at(j)->as_Mem();
 394       if (s->is_Load()) {
 395         int vw = vector_width_in_bytes(s);
 396         assert(vw > 1, "sanity");
 397         SWPointer p(s, this);
 398         if (cmp_ct.at(j) >  max_ct ||
 399             cmp_ct.at(j) == max_ct &&
 400               (vw >  max_vw ||
 401                vw == max_vw &&
 402                 (data_size(s) <  min_size ||
 403                  data_size(s) == min_size &&
 404                    (p.offset_in_bytes() < min_iv_offset)))) {
 405           max_ct = cmp_ct.at(j);
 406           max_vw = vw;
 407           max_idx = j;
 408           min_size = data_size(s);
 409           min_iv_offset = p.offset_in_bytes();
 410         }
 411       }
 412     }
 413   }
 414 
 415 #ifdef ASSERT
 416   if (TraceSuperWord && Verbose) {
 417     tty->print_cr("\nVector memops after find_align_to_refs");
 418     for (uint i = 0; i < memops.size(); i++) {
 419       MemNode* s = memops.at(i)->as_Mem();
 420       s->dump();
 421     }
 422   }
 423 #endif
 424 
 425   if (max_ct > 0) {
 426 #ifdef ASSERT
 427     if (TraceSuperWord) {
 428       tty->print("\nVector align to node: ");
 429       memops.at(max_idx)->as_Mem()->dump();
 430     }
 431 #endif
 432     return memops.at(max_idx)->as_Mem();
 433   }
 434   return NULL;
 435 }
 436 
 437 //------------------------------ref_is_alignable---------------------------
 438 // Can the preloop align the reference to position zero in the vector?
 439 bool SuperWord::ref_is_alignable(SWPointer& p) {
 440   if (!p.has_iv()) {
 441     return true;   // no induction variable
 442   }
 443   CountedLoopEndNode* pre_end = get_pre_loop_end(lp()->as_CountedLoop());
 444   assert(pre_end != NULL, "we must have a correct pre-loop");
 445   assert(pre_end->stride_is_con(), "pre loop stride is constant");
 446   int preloop_stride = pre_end->stride_con();
 447 
 448   int span = preloop_stride * p.scale_in_bytes();
 449 
 450   // Stride one accesses are alignable.
 451   if (ABS(span) == p.memory_size())
 452     return true;
 453 
 454   // If initial offset from start of object is computable,
 455   // compute alignment within the vector.
 456   int vw = vector_width_in_bytes(p.mem());
 457   assert(vw > 1, "sanity");
 458   if (vw % span == 0) {
 459     Node* init_nd = pre_end->init_trip();
 460     if (init_nd->is_Con() && p.invar() == NULL) {
 461       int init = init_nd->bottom_type()->is_int()->get_con();
 462 
 463       int init_offset = init * p.scale_in_bytes() + p.offset_in_bytes();
 464       assert(init_offset >= 0, "positive offset from object start");
 465 
 466       if (span > 0) {
 467         return (vw - (init_offset % vw)) % span == 0;
 468       } else {
 469         assert(span < 0, "nonzero stride * scale");
 470         return (init_offset % vw) % -span == 0;
 471       }
 472     }
 473   }
 474   return false;
 475 }
 476 
 477 //---------------------------get_iv_adjustment---------------------------
 478 // Calculate loop's iv adjustment for this memory ops.
 479 int SuperWord::get_iv_adjustment(MemNode* mem_ref) {
 480   SWPointer align_to_ref_p(mem_ref, this);
 481   int offset = align_to_ref_p.offset_in_bytes();
 482   int scale  = align_to_ref_p.scale_in_bytes();
 483   int vw       = vector_width_in_bytes(mem_ref);
 484   assert(vw > 1, "sanity");
 485   int stride_sign   = (scale * iv_stride()) > 0 ? 1 : -1;
 486   // At least one iteration is executed in pre-loop by default. As result
 487   // several iterations are needed to align memory operations in main-loop even
 488   // if offset is 0.
 489   int iv_adjustment_in_bytes = (stride_sign * vw - (offset % vw));
 490   int elt_size = align_to_ref_p.memory_size();
 491   assert(((ABS(iv_adjustment_in_bytes) % elt_size) == 0),
 492          err_msg_res("(%d) should be divisible by (%d)", iv_adjustment_in_bytes, elt_size));
 493   int iv_adjustment = iv_adjustment_in_bytes/elt_size;
 494 
 495 #ifndef PRODUCT
 496   if (TraceSuperWord)
 497     tty->print_cr("\noffset = %d iv_adjust = %d elt_size = %d scale = %d iv_stride = %d vect_size %d",
 498                   offset, iv_adjustment, elt_size, scale, iv_stride(), vw);
 499 #endif
 500   return iv_adjustment;
 501 }
 502 
 503 //---------------------------dependence_graph---------------------------
 504 // Construct dependency graph.
 505 // Add dependence edges to load/store nodes for memory dependence
 506 //    A.out()->DependNode.in(1) and DependNode.out()->B.prec(x)
 507 void SuperWord::dependence_graph() {
 508   // First, assign a dependence node to each memory node
 509   for (int i = 0; i < _block.length(); i++ ) {
 510     Node *n = _block.at(i);
 511     if (n->is_Mem() || n->is_Phi() && n->bottom_type() == Type::MEMORY) {
 512       _dg.make_node(n);
 513     }
 514   }
 515 
 516   // For each memory slice, create the dependences
 517   for (int i = 0; i < _mem_slice_head.length(); i++) {
 518     Node* n      = _mem_slice_head.at(i);
 519     Node* n_tail = _mem_slice_tail.at(i);
 520 
 521     // Get slice in predecessor order (last is first)
 522     mem_slice_preds(n_tail, n, _nlist);
 523 
 524     // Make the slice dependent on the root
 525     DepMem* slice = _dg.dep(n);
 526     _dg.make_edge(_dg.root(), slice);
 527 
 528     // Create a sink for the slice
 529     DepMem* slice_sink = _dg.make_node(NULL);
 530     _dg.make_edge(slice_sink, _dg.tail());
 531 
 532     // Now visit each pair of memory ops, creating the edges
 533     for (int j = _nlist.length() - 1; j >= 0 ; j--) {
 534       Node* s1 = _nlist.at(j);
 535 
 536       // If no dependency yet, use slice
 537       if (_dg.dep(s1)->in_cnt() == 0) {
 538         _dg.make_edge(slice, s1);
 539       }
 540       SWPointer p1(s1->as_Mem(), this);
 541       bool sink_dependent = true;
 542       for (int k = j - 1; k >= 0; k--) {
 543         Node* s2 = _nlist.at(k);
 544         if (s1->is_Load() && s2->is_Load())
 545           continue;
 546         SWPointer p2(s2->as_Mem(), this);
 547 
 548         int cmp = p1.cmp(p2);
 549         if (SuperWordRTDepCheck &&
 550             p1.base() != p2.base() && p1.valid() && p2.valid()) {
 551           // Create a runtime check to disambiguate
 552           OrderedPair pp(p1.base(), p2.base());
 553           _disjoint_ptrs.append_if_missing(pp);
 554         } else if (!SWPointer::not_equal(cmp)) {
 555           // Possibly same address
 556           _dg.make_edge(s1, s2);
 557           sink_dependent = false;
 558         }
 559       }
 560       if (sink_dependent) {
 561         _dg.make_edge(s1, slice_sink);
 562       }
 563     }
 564 #ifndef PRODUCT
 565     if (TraceSuperWord) {
 566       tty->print_cr("\nDependence graph for slice: %d", n->_idx);
 567       for (int q = 0; q < _nlist.length(); q++) {
 568         _dg.print(_nlist.at(q));
 569       }
 570       tty->cr();
 571     }
 572 #endif
 573     _nlist.clear();
 574   }
 575 
 576 #ifndef PRODUCT
 577   if (TraceSuperWord) {
 578     tty->print_cr("\ndisjoint_ptrs: %s", _disjoint_ptrs.length() > 0 ? "" : "NONE");
 579     for (int r = 0; r < _disjoint_ptrs.length(); r++) {
 580       _disjoint_ptrs.at(r).print();
 581       tty->cr();
 582     }
 583     tty->cr();
 584   }
 585 #endif
 586 }
 587 
 588 //---------------------------mem_slice_preds---------------------------
 589 // Return a memory slice (node list) in predecessor order starting at "start"
 590 void SuperWord::mem_slice_preds(Node* start, Node* stop, GrowableArray<Node*> &preds) {
 591   assert(preds.length() == 0, "start empty");
 592   Node* n = start;
 593   Node* prev = NULL;
 594   while (true) {
 595     assert(in_bb(n), "must be in block");
 596     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 597       Node* out = n->fast_out(i);
 598       if (out->is_Load()) {
 599         if (in_bb(out)) {
 600           preds.push(out);
 601         }
 602       } else {
 603         // FIXME
 604         if (out->is_MergeMem() && !in_bb(out)) {
 605           // Either unrolling is causing a memory edge not to disappear,
 606           // or need to run igvn.optimize() again before SLP
 607         } else if (out->is_Phi() && out->bottom_type() == Type::MEMORY && !in_bb(out)) {
 608           // Ditto.  Not sure what else to check further.
 609         } else if (out->Opcode() == Op_StoreCM && out->in(MemNode::OopStore) == n) {
 610           // StoreCM has an input edge used as a precedence edge.
 611           // Maybe an issue when oop stores are vectorized.
 612         } else {
 613           assert(out == prev || prev == NULL, "no branches off of store slice");
 614         }
 615       }
 616     }
 617     if (n == stop) break;
 618     preds.push(n);
 619     prev = n;
 620     assert(n->is_Mem(), err_msg_res("unexpected node %s", n->Name()));
 621     n = n->in(MemNode::Memory);
 622   }
 623 }
 624 
 625 //------------------------------stmts_can_pack---------------------------
 626 // Can s1 and s2 be in a pack with s1 immediately preceding s2 and
 627 // s1 aligned at "align"
 628 bool SuperWord::stmts_can_pack(Node* s1, Node* s2, int align) {
 629 
 630   // Do not use superword for non-primitives
 631   BasicType bt1 = velt_basic_type(s1);
 632   BasicType bt2 = velt_basic_type(s2);
 633   if(!is_java_primitive(bt1) || !is_java_primitive(bt2))
 634     return false;
 635   if (Matcher::max_vector_size(bt1) < 2) {
 636     return false; // No vectors for this type
 637   }
 638 
 639   if (isomorphic(s1, s2)) {
 640     if (independent(s1, s2)) {
 641       if (!exists_at(s1, 0) && !exists_at(s2, 1)) {
 642         if (!s1->is_Mem() || are_adjacent_refs(s1, s2)) {
 643           int s1_align = alignment(s1);
 644           int s2_align = alignment(s2);
 645           if (s1_align == top_align || s1_align == align) {
 646             if (s2_align == top_align || s2_align == align + data_size(s1)) {
 647               return true;
 648             }
 649           }
 650         }
 651       }
 652     }
 653   }
 654   return false;
 655 }
 656 
 657 //------------------------------exists_at---------------------------
 658 // Does s exist in a pack at position pos?
 659 bool SuperWord::exists_at(Node* s, uint pos) {
 660   for (int i = 0; i < _packset.length(); i++) {
 661     Node_List* p = _packset.at(i);
 662     if (p->at(pos) == s) {
 663       return true;
 664     }
 665   }
 666   return false;
 667 }
 668 
 669 //------------------------------are_adjacent_refs---------------------------
 670 // Is s1 immediately before s2 in memory?
 671 bool SuperWord::are_adjacent_refs(Node* s1, Node* s2) {
 672   if (!s1->is_Mem() || !s2->is_Mem()) return false;
 673   if (!in_bb(s1)    || !in_bb(s2))    return false;
 674 
 675   // Do not use superword for non-primitives
 676   if (!is_java_primitive(s1->as_Mem()->memory_type()) ||
 677       !is_java_primitive(s2->as_Mem()->memory_type())) {
 678     return false;
 679   }
 680 
 681   // FIXME - co_locate_pack fails on Stores in different mem-slices, so
 682   // only pack memops that are in the same alias set until that's fixed.
 683   if (_phase->C->get_alias_index(s1->as_Mem()->adr_type()) !=
 684       _phase->C->get_alias_index(s2->as_Mem()->adr_type()))
 685     return false;
 686   SWPointer p1(s1->as_Mem(), this);
 687   SWPointer p2(s2->as_Mem(), this);
 688   if (p1.base() != p2.base() || !p1.comparable(p2)) return false;
 689   int diff = p2.offset_in_bytes() - p1.offset_in_bytes();
 690   return diff == data_size(s1);
 691 }
 692 
 693 //------------------------------isomorphic---------------------------
 694 // Are s1 and s2 similar?
 695 bool SuperWord::isomorphic(Node* s1, Node* s2) {
 696   if (s1->Opcode() != s2->Opcode()) return false;
 697   if (s1->req() != s2->req()) return false;
 698   if (s1->in(0) != s2->in(0)) return false;
 699   if (!same_velt_type(s1, s2)) return false;
 700   return true;
 701 }
 702 
 703 //------------------------------independent---------------------------
 704 // Is there no data path from s1 to s2 or s2 to s1?
 705 bool SuperWord::independent(Node* s1, Node* s2) {
 706   //  assert(s1->Opcode() == s2->Opcode(), "check isomorphic first");
 707   int d1 = depth(s1);
 708   int d2 = depth(s2);
 709   if (d1 == d2) return s1 != s2;
 710   Node* deep    = d1 > d2 ? s1 : s2;
 711   Node* shallow = d1 > d2 ? s2 : s1;
 712 
 713   visited_clear();
 714 
 715   return independent_path(shallow, deep);
 716 }
 717 
 718 //------------------------------independent_path------------------------------
 719 // Helper for independent
 720 bool SuperWord::independent_path(Node* shallow, Node* deep, uint dp) {
 721   if (dp >= 1000) return false; // stop deep recursion
 722   visited_set(deep);
 723   int shal_depth = depth(shallow);
 724   assert(shal_depth <= depth(deep), "must be");
 725   for (DepPreds preds(deep, _dg); !preds.done(); preds.next()) {
 726     Node* pred = preds.current();
 727     if (in_bb(pred) && !visited_test(pred)) {
 728       if (shallow == pred) {
 729         return false;
 730       }
 731       if (shal_depth < depth(pred) && !independent_path(shallow, pred, dp+1)) {
 732         return false;
 733       }
 734     }
 735   }
 736   return true;
 737 }
 738 
 739 //------------------------------set_alignment---------------------------
 740 void SuperWord::set_alignment(Node* s1, Node* s2, int align) {
 741   set_alignment(s1, align);
 742   if (align == top_align || align == bottom_align) {
 743     set_alignment(s2, align);
 744   } else {
 745     set_alignment(s2, align + data_size(s1));
 746   }
 747 }
 748 
 749 //------------------------------data_size---------------------------
 750 int SuperWord::data_size(Node* s) {
 751   int bsize = type2aelembytes(velt_basic_type(s));
 752   assert(bsize != 0, "valid size");
 753   return bsize;
 754 }
 755 
 756 //------------------------------extend_packlist---------------------------
 757 // Extend packset by following use->def and def->use links from pack members.
 758 void SuperWord::extend_packlist() {
 759   bool changed;
 760   do {
 761     changed = false;
 762     for (int i = 0; i < _packset.length(); i++) {
 763       Node_List* p = _packset.at(i);
 764       changed |= follow_use_defs(p);
 765       changed |= follow_def_uses(p);
 766     }
 767   } while (changed);
 768 
 769 #ifndef PRODUCT
 770   if (TraceSuperWord) {
 771     tty->print_cr("\nAfter extend_packlist");
 772     print_packset();
 773   }
 774 #endif
 775 }
 776 
 777 //------------------------------follow_use_defs---------------------------
 778 // Extend the packset by visiting operand definitions of nodes in pack p
 779 bool SuperWord::follow_use_defs(Node_List* p) {
 780   assert(p->size() == 2, "just checking");
 781   Node* s1 = p->at(0);
 782   Node* s2 = p->at(1);
 783   assert(s1->req() == s2->req(), "just checking");
 784   assert(alignment(s1) + data_size(s1) == alignment(s2), "just checking");
 785 
 786   if (s1->is_Load()) return false;
 787 
 788   int align = alignment(s1);
 789   bool changed = false;
 790   int start = s1->is_Store() ? MemNode::ValueIn   : 1;
 791   int end   = s1->is_Store() ? MemNode::ValueIn+1 : s1->req();
 792   for (int j = start; j < end; j++) {
 793     Node* t1 = s1->in(j);
 794     Node* t2 = s2->in(j);
 795     if (!in_bb(t1) || !in_bb(t2))
 796       continue;
 797     if (stmts_can_pack(t1, t2, align)) {
 798       if (est_savings(t1, t2) >= 0) {
 799         Node_List* pair = new Node_List();
 800         pair->push(t1);
 801         pair->push(t2);
 802         _packset.append(pair);
 803         set_alignment(t1, t2, align);
 804         changed = true;
 805       }
 806     }
 807   }
 808   return changed;
 809 }
 810 
 811 //------------------------------follow_def_uses---------------------------
 812 // Extend the packset by visiting uses of nodes in pack p
 813 bool SuperWord::follow_def_uses(Node_List* p) {
 814   bool changed = false;
 815   Node* s1 = p->at(0);
 816   Node* s2 = p->at(1);
 817   assert(p->size() == 2, "just checking");
 818   assert(s1->req() == s2->req(), "just checking");
 819   assert(alignment(s1) + data_size(s1) == alignment(s2), "just checking");
 820 
 821   if (s1->is_Store()) return false;
 822 
 823   int align = alignment(s1);
 824   int savings = -1;
 825   Node* u1 = NULL;
 826   Node* u2 = NULL;
 827   for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
 828     Node* t1 = s1->fast_out(i);
 829     if (!in_bb(t1)) continue;
 830     for (DUIterator_Fast jmax, j = s2->fast_outs(jmax); j < jmax; j++) {
 831       Node* t2 = s2->fast_out(j);
 832       if (!in_bb(t2)) continue;
 833       if (!opnd_positions_match(s1, t1, s2, t2))
 834         continue;
 835       if (stmts_can_pack(t1, t2, align)) {
 836         int my_savings = est_savings(t1, t2);
 837         if (my_savings > savings) {
 838           savings = my_savings;
 839           u1 = t1;
 840           u2 = t2;
 841         }
 842       }
 843     }
 844   }
 845   if (savings >= 0) {
 846     Node_List* pair = new Node_List();
 847     pair->push(u1);
 848     pair->push(u2);
 849     _packset.append(pair);
 850     set_alignment(u1, u2, align);
 851     changed = true;
 852   }
 853   return changed;
 854 }
 855 
 856 //---------------------------opnd_positions_match-------------------------
 857 // Is the use of d1 in u1 at the same operand position as d2 in u2?
 858 bool SuperWord::opnd_positions_match(Node* d1, Node* u1, Node* d2, Node* u2) {
 859   uint ct = u1->req();
 860   if (ct != u2->req()) return false;
 861   uint i1 = 0;
 862   uint i2 = 0;
 863   do {
 864     for (i1++; i1 < ct; i1++) if (u1->in(i1) == d1) break;
 865     for (i2++; i2 < ct; i2++) if (u2->in(i2) == d2) break;
 866     if (i1 != i2) {
 867       if ((i1 == (3-i2)) && (u2->is_Add() || u2->is_Mul())) {
 868         // Further analysis relies on operands position matching.
 869         u2->swap_edges(i1, i2);
 870       } else {
 871         return false;
 872       }
 873     }
 874   } while (i1 < ct);
 875   return true;
 876 }
 877 
 878 //------------------------------est_savings---------------------------
 879 // Estimate the savings from executing s1 and s2 as a pack
 880 int SuperWord::est_savings(Node* s1, Node* s2) {
 881   int save_in = 2 - 1; // 2 operations per instruction in packed form
 882 
 883   // inputs
 884   for (uint i = 1; i < s1->req(); i++) {
 885     Node* x1 = s1->in(i);
 886     Node* x2 = s2->in(i);
 887     if (x1 != x2) {
 888       if (are_adjacent_refs(x1, x2)) {
 889         save_in += adjacent_profit(x1, x2);
 890       } else if (!in_packset(x1, x2)) {
 891         save_in -= pack_cost(2);
 892       } else {
 893         save_in += unpack_cost(2);
 894       }
 895     }
 896   }
 897 
 898   // uses of result
 899   uint ct = 0;
 900   int save_use = 0;
 901   for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
 902     Node* s1_use = s1->fast_out(i);
 903     for (int j = 0; j < _packset.length(); j++) {
 904       Node_List* p = _packset.at(j);
 905       if (p->at(0) == s1_use) {
 906         for (DUIterator_Fast kmax, k = s2->fast_outs(kmax); k < kmax; k++) {
 907           Node* s2_use = s2->fast_out(k);
 908           if (p->at(p->size()-1) == s2_use) {
 909             ct++;
 910             if (are_adjacent_refs(s1_use, s2_use)) {
 911               save_use += adjacent_profit(s1_use, s2_use);
 912             }
 913           }
 914         }
 915       }
 916     }
 917   }
 918 
 919   if (ct < s1->outcnt()) save_use += unpack_cost(1);
 920   if (ct < s2->outcnt()) save_use += unpack_cost(1);
 921 
 922   return MAX2(save_in, save_use);
 923 }
 924 
 925 //------------------------------costs---------------------------
 926 int SuperWord::adjacent_profit(Node* s1, Node* s2) { return 2; }
 927 int SuperWord::pack_cost(int ct)   { return ct; }
 928 int SuperWord::unpack_cost(int ct) { return ct; }
 929 
 930 //------------------------------combine_packs---------------------------
 931 // Combine packs A and B with A.last == B.first into A.first..,A.last,B.second,..B.last
 932 void SuperWord::combine_packs() {
 933   bool changed = true;
 934   // Combine packs regardless max vector size.
 935   while (changed) {
 936     changed = false;
 937     for (int i = 0; i < _packset.length(); i++) {
 938       Node_List* p1 = _packset.at(i);
 939       if (p1 == NULL) continue;
 940       for (int j = 0; j < _packset.length(); j++) {
 941         Node_List* p2 = _packset.at(j);
 942         if (p2 == NULL) continue;
 943         if (i == j) continue;
 944         if (p1->at(p1->size()-1) == p2->at(0)) {
 945           for (uint k = 1; k < p2->size(); k++) {
 946             p1->push(p2->at(k));
 947           }
 948           _packset.at_put(j, NULL);
 949           changed = true;
 950         }
 951       }
 952     }
 953   }
 954 
 955   // Split packs which have size greater then max vector size.
 956   for (int i = 0; i < _packset.length(); i++) {
 957     Node_List* p1 = _packset.at(i);
 958     if (p1 != NULL) {
 959       BasicType bt = velt_basic_type(p1->at(0));
 960       uint max_vlen = Matcher::max_vector_size(bt); // Max elements in vector
 961       assert(is_power_of_2(max_vlen), "sanity");
 962       uint psize = p1->size();
 963       if (!is_power_of_2(psize)) {
 964         // Skip pack which can't be vector.
 965         // case1: for(...) { a[i] = i; }    elements values are different (i+x)
 966         // case2: for(...) { a[i] = b[i+1]; }  can't align both, load and store
 967         _packset.at_put(i, NULL);
 968         continue;
 969       }
 970       if (psize > max_vlen) {
 971         Node_List* pack = new Node_List();
 972         for (uint j = 0; j < psize; j++) {
 973           pack->push(p1->at(j));
 974           if (pack->size() >= max_vlen) {
 975             assert(is_power_of_2(pack->size()), "sanity");
 976             _packset.append(pack);
 977             pack = new Node_List();
 978           }
 979         }
 980         _packset.at_put(i, NULL);
 981       }
 982     }
 983   }
 984 
 985   // Compress list.
 986   for (int i = _packset.length() - 1; i >= 0; i--) {
 987     Node_List* p1 = _packset.at(i);
 988     if (p1 == NULL) {
 989       _packset.remove_at(i);
 990     }
 991   }
 992 
 993 #ifndef PRODUCT
 994   if (TraceSuperWord) {
 995     tty->print_cr("\nAfter combine_packs");
 996     print_packset();
 997   }
 998 #endif
 999 }
1000 
1001 //-----------------------------construct_my_pack_map--------------------------
1002 // Construct the map from nodes to packs.  Only valid after the
1003 // point where a node is only in one pack (after combine_packs).
1004 void SuperWord::construct_my_pack_map() {
1005   Node_List* rslt = NULL;
1006   for (int i = 0; i < _packset.length(); i++) {
1007     Node_List* p = _packset.at(i);
1008     for (uint j = 0; j < p->size(); j++) {
1009       Node* s = p->at(j);
1010       assert(my_pack(s) == NULL, "only in one pack");
1011       set_my_pack(s, p);
1012     }
1013   }
1014 }
1015 
1016 //------------------------------filter_packs---------------------------
1017 // Remove packs that are not implemented or not profitable.
1018 void SuperWord::filter_packs() {
1019 
1020   // Remove packs that are not implemented
1021   for (int i = _packset.length() - 1; i >= 0; i--) {
1022     Node_List* pk = _packset.at(i);
1023     bool impl = implemented(pk);
1024     if (!impl) {
1025 #ifndef PRODUCT
1026       if (TraceSuperWord && Verbose) {
1027         tty->print_cr("Unimplemented");
1028         pk->at(0)->dump();
1029       }
1030 #endif
1031       remove_pack_at(i);
1032     }
1033   }
1034 
1035   // Remove packs that are not profitable
1036   bool changed;
1037   do {
1038     changed = false;
1039     for (int i = _packset.length() - 1; i >= 0; i--) {
1040       Node_List* pk = _packset.at(i);
1041       bool prof = profitable(pk);
1042       if (!prof) {
1043 #ifndef PRODUCT
1044         if (TraceSuperWord && Verbose) {
1045           tty->print_cr("Unprofitable");
1046           pk->at(0)->dump();
1047         }
1048 #endif
1049         remove_pack_at(i);
1050         changed = true;
1051       }
1052     }
1053   } while (changed);
1054 
1055 #ifndef PRODUCT
1056   if (TraceSuperWord) {
1057     tty->print_cr("\nAfter filter_packs");
1058     print_packset();
1059     tty->cr();
1060   }
1061 #endif
1062 }
1063 
1064 //------------------------------implemented---------------------------
1065 // Can code be generated for pack p?
1066 bool SuperWord::implemented(Node_List* p) {
1067   Node* p0 = p->at(0);
1068   return VectorNode::implemented(p0->Opcode(), p->size(), velt_basic_type(p0));
1069 }
1070 
1071 //------------------------------same_inputs--------------------------
1072 // For pack p, are all idx operands the same?
1073 static bool same_inputs(Node_List* p, int idx) {
1074   Node* p0 = p->at(0);
1075   uint vlen = p->size();
1076   Node* p0_def = p0->in(idx);
1077   for (uint i = 1; i < vlen; i++) {
1078     Node* pi = p->at(i);
1079     Node* pi_def = pi->in(idx);
1080     if (p0_def != pi_def)
1081       return false;
1082   }
1083   return true;
1084 }
1085 
1086 //------------------------------profitable---------------------------
1087 // For pack p, are all operands and all uses (with in the block) vector?
1088 bool SuperWord::profitable(Node_List* p) {
1089   Node* p0 = p->at(0);
1090   uint start, end;
1091   VectorNode::vector_operands(p0, &start, &end);
1092 
1093   // Return false if some inputs are not vectors or vectors with different
1094   // size or alignment.
1095   // Also, for now, return false if not scalar promotion case when inputs are
1096   // the same. Later, implement PackNode and allow differing, non-vector inputs
1097   // (maybe just the ones from outside the block.)
1098   for (uint i = start; i < end; i++) {
1099     if (!is_vector_use(p0, i))
1100       return false;
1101   }
1102   if (VectorNode::is_shift(p0)) {
1103     // For now, return false if shift count is vector or not scalar promotion
1104     // case (different shift counts) because it is not supported yet.
1105     Node* cnt = p0->in(2);
1106     Node_List* cnt_pk = my_pack(cnt);
1107     if (cnt_pk != NULL)
1108       return false;
1109     if (!same_inputs(p, 2))
1110       return false;
1111   }
1112   if (!p0->is_Store()) {
1113     // For now, return false if not all uses are vector.
1114     // Later, implement ExtractNode and allow non-vector uses (maybe
1115     // just the ones outside the block.)
1116     for (uint i = 0; i < p->size(); i++) {
1117       Node* def = p->at(i);
1118       for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
1119         Node* use = def->fast_out(j);
1120         for (uint k = 0; k < use->req(); k++) {
1121           Node* n = use->in(k);
1122           if (def == n) {
1123             if (!is_vector_use(use, k)) {
1124               return false;
1125             }
1126           }
1127         }
1128       }
1129     }
1130   }
1131   return true;
1132 }
1133 
1134 //------------------------------schedule---------------------------
1135 // Adjust the memory graph for the packed operations
1136 void SuperWord::schedule() {
1137 
1138   // Co-locate in the memory graph the members of each memory pack
1139   for (int i = 0; i < _packset.length(); i++) {
1140     co_locate_pack(_packset.at(i));
1141   }
1142 }
1143 
1144 //-------------------------------remove_and_insert-------------------
1145 // Remove "current" from its current position in the memory graph and insert
1146 // it after the appropriate insertion point (lip or uip).
1147 void SuperWord::remove_and_insert(MemNode *current, MemNode *prev, MemNode *lip,
1148                                   Node *uip, Unique_Node_List &sched_before) {
1149   Node* my_mem = current->in(MemNode::Memory);
1150   bool sched_up = sched_before.member(current);
1151 
1152   // remove current_store from its current position in the memmory graph
1153   for (DUIterator i = current->outs(); current->has_out(i); i++) {
1154     Node* use = current->out(i);
1155     if (use->is_Mem()) {
1156       assert(use->in(MemNode::Memory) == current, "must be");
1157       if (use == prev) { // connect prev to my_mem
1158           _igvn.replace_input_of(use, MemNode::Memory, my_mem);
1159           --i; //deleted this edge; rescan position
1160       } else if (sched_before.member(use)) {
1161         if (!sched_up) { // Will be moved together with current
1162           _igvn.replace_input_of(use, MemNode::Memory, uip);
1163           --i; //deleted this edge; rescan position
1164         }
1165       } else {
1166         if (sched_up) { // Will be moved together with current
1167           _igvn.replace_input_of(use, MemNode::Memory, lip);
1168           --i; //deleted this edge; rescan position
1169         }
1170       }
1171     }
1172   }
1173 
1174   Node *insert_pt =  sched_up ?  uip : lip;
1175 
1176   // all uses of insert_pt's memory state should use current's instead
1177   for (DUIterator i = insert_pt->outs(); insert_pt->has_out(i); i++) {
1178     Node* use = insert_pt->out(i);
1179     if (use->is_Mem()) {
1180       assert(use->in(MemNode::Memory) == insert_pt, "must be");
1181       _igvn.replace_input_of(use, MemNode::Memory, current);
1182       --i; //deleted this edge; rescan position
1183     } else if (!sched_up && use->is_Phi() && use->bottom_type() == Type::MEMORY) {
1184       uint pos; //lip (lower insert point) must be the last one in the memory slice
1185       for (pos=1; pos < use->req(); pos++) {
1186         if (use->in(pos) == insert_pt) break;
1187       }
1188       _igvn.replace_input_of(use, pos, current);
1189       --i;
1190     }
1191   }
1192 
1193   //connect current to insert_pt
1194   _igvn.replace_input_of(current, MemNode::Memory, insert_pt);
1195 }
1196 
1197 //------------------------------co_locate_pack----------------------------------
1198 // To schedule a store pack, we need to move any sandwiched memory ops either before
1199 // or after the pack, based upon dependence information:
1200 // (1) If any store in the pack depends on the sandwiched memory op, the
1201 //     sandwiched memory op must be scheduled BEFORE the pack;
1202 // (2) If a sandwiched memory op depends on any store in the pack, the
1203 //     sandwiched memory op must be scheduled AFTER the pack;
1204 // (3) If a sandwiched memory op (say, memA) depends on another sandwiched
1205 //     memory op (say memB), memB must be scheduled before memA. So, if memA is
1206 //     scheduled before the pack, memB must also be scheduled before the pack;
1207 // (4) If there is no dependence restriction for a sandwiched memory op, we simply
1208 //     schedule this store AFTER the pack
1209 // (5) We know there is no dependence cycle, so there in no other case;
1210 // (6) Finally, all memory ops in another single pack should be moved in the same direction.
1211 //
1212 // To schedule a load pack, we use the memory state of either the first or the last load in
1213 // the pack, based on the dependence constraint.
1214 void SuperWord::co_locate_pack(Node_List* pk) {
1215   if (pk->at(0)->is_Store()) {
1216     MemNode* first     = executed_first(pk)->as_Mem();
1217     MemNode* last      = executed_last(pk)->as_Mem();
1218     Unique_Node_List schedule_before_pack;
1219     Unique_Node_List memops;
1220 
1221     MemNode* current   = last->in(MemNode::Memory)->as_Mem();
1222     MemNode* previous  = last;
1223     while (true) {
1224       assert(in_bb(current), "stay in block");
1225       memops.push(previous);
1226       for (DUIterator i = current->outs(); current->has_out(i); i++) {
1227         Node* use = current->out(i);
1228         if (use->is_Mem() && use != previous)
1229           memops.push(use);
1230       }
1231       if (current == first) break;
1232       previous = current;
1233       current  = current->in(MemNode::Memory)->as_Mem();
1234     }
1235 
1236     // determine which memory operations should be scheduled before the pack
1237     for (uint i = 1; i < memops.size(); i++) {
1238       Node *s1 = memops.at(i);
1239       if (!in_pack(s1, pk) && !schedule_before_pack.member(s1)) {
1240         for (uint j = 0; j< i; j++) {
1241           Node *s2 = memops.at(j);
1242           if (!independent(s1, s2)) {
1243             if (in_pack(s2, pk) || schedule_before_pack.member(s2)) {
1244               schedule_before_pack.push(s1); // s1 must be scheduled before
1245               Node_List* mem_pk = my_pack(s1);
1246               if (mem_pk != NULL) {
1247                 for (uint ii = 0; ii < mem_pk->size(); ii++) {
1248                   Node* s = mem_pk->at(ii);  // follow partner
1249                   if (memops.member(s) && !schedule_before_pack.member(s))
1250                     schedule_before_pack.push(s);
1251                 }
1252               }
1253               break;
1254             }
1255           }
1256         }
1257       }
1258     }
1259 
1260     Node*    upper_insert_pt = first->in(MemNode::Memory);
1261     // Following code moves loads connected to upper_insert_pt below aliased stores.
1262     // Collect such loads here and reconnect them back to upper_insert_pt later.
1263     memops.clear();
1264     for (DUIterator i = upper_insert_pt->outs(); upper_insert_pt->has_out(i); i++) {
1265       Node* use = upper_insert_pt->out(i);
1266       if (!use->is_Store())
1267         memops.push(use);
1268     }
1269 
1270     MemNode* lower_insert_pt = last;
1271     previous                 = last; //previous store in pk
1272     current                  = last->in(MemNode::Memory)->as_Mem();
1273 
1274     // start scheduling from "last" to "first"
1275     while (true) {
1276       assert(in_bb(current), "stay in block");
1277       assert(in_pack(previous, pk), "previous stays in pack");
1278       Node* my_mem = current->in(MemNode::Memory);
1279 
1280       if (in_pack(current, pk)) {
1281         // Forward users of my memory state (except "previous) to my input memory state
1282         for (DUIterator i = current->outs(); current->has_out(i); i++) {
1283           Node* use = current->out(i);
1284           if (use->is_Mem() && use != previous) {
1285             assert(use->in(MemNode::Memory) == current, "must be");
1286             if (schedule_before_pack.member(use)) {
1287               _igvn.replace_input_of(use, MemNode::Memory, upper_insert_pt);
1288             } else {
1289               _igvn.replace_input_of(use, MemNode::Memory, lower_insert_pt);
1290             }
1291             --i; // deleted this edge; rescan position
1292           }
1293         }
1294         previous = current;
1295       } else { // !in_pack(current, pk) ==> a sandwiched store
1296         remove_and_insert(current, previous, lower_insert_pt, upper_insert_pt, schedule_before_pack);
1297       }
1298 
1299       if (current == first) break;
1300       current = my_mem->as_Mem();
1301     } // end while
1302 
1303     // Reconnect loads back to upper_insert_pt.
1304     for (uint i = 0; i < memops.size(); i++) {
1305       Node *ld = memops.at(i);
1306       if (ld->in(MemNode::Memory) != upper_insert_pt) {
1307         _igvn.replace_input_of(ld, MemNode::Memory, upper_insert_pt);
1308       }
1309     }
1310   } else if (pk->at(0)->is_Load()) { //load
1311     // all loads in the pack should have the same memory state. By default,
1312     // we use the memory state of the last load. However, if any load could
1313     // not be moved down due to the dependence constraint, we use the memory
1314     // state of the first load.
1315     Node* last_mem  = executed_last(pk)->in(MemNode::Memory);
1316     Node* first_mem = executed_first(pk)->in(MemNode::Memory);
1317     bool schedule_last = true;
1318     for (uint i = 0; i < pk->size(); i++) {
1319       Node* ld = pk->at(i);
1320       for (Node* current = last_mem; current != ld->in(MemNode::Memory);
1321            current=current->in(MemNode::Memory)) {
1322         assert(current != first_mem, "corrupted memory graph");
1323         if(current->is_Mem() && !independent(current, ld)){
1324           schedule_last = false; // a later store depends on this load
1325           break;
1326         }
1327       }
1328     }
1329 
1330     Node* mem_input = schedule_last ? last_mem : first_mem;
1331     _igvn.hash_delete(mem_input);
1332     // Give each load the same memory state
1333     for (uint i = 0; i < pk->size(); i++) {
1334       LoadNode* ld = pk->at(i)->as_Load();
1335       _igvn.replace_input_of(ld, MemNode::Memory, mem_input);
1336     }
1337   }
1338 }
1339 
1340 //------------------------------output---------------------------
1341 // Convert packs into vector node operations
1342 void SuperWord::output() {
1343   if (_packset.length() == 0) return;
1344 
1345 #ifndef PRODUCT
1346   if (TraceLoopOpts) {
1347     tty->print("SuperWord    ");
1348     lpt()->dump_head();
1349   }
1350 #endif
1351 
1352   // MUST ENSURE main loop's initial value is properly aligned:
1353   //  (iv_initial_value + min_iv_offset) % vector_width_in_bytes() == 0
1354 
1355   align_initial_loop_index(align_to_ref());
1356 
1357   // Insert extract (unpack) operations for scalar uses
1358   for (int i = 0; i < _packset.length(); i++) {
1359     insert_extracts(_packset.at(i));
1360   }
1361 
1362   Compile* C = _phase->C;
1363   uint max_vlen_in_bytes = 0;
1364   for (int i = 0; i < _block.length(); i++) {
1365     Node* n = _block.at(i);
1366     Node_List* p = my_pack(n);
1367     if (p && n == executed_last(p)) {
1368       uint vlen = p->size();
1369       uint vlen_in_bytes = 0;
1370       Node* vn = NULL;
1371       Node* low_adr = p->at(0);
1372       Node* first   = executed_first(p);
1373       int   opc = n->Opcode();
1374       if (n->is_Load()) {
1375         Node* ctl = n->in(MemNode::Control);
1376         Node* mem = first->in(MemNode::Memory);
1377         Node* adr = low_adr->in(MemNode::Address);
1378         const TypePtr* atyp = n->adr_type();
1379         vn = LoadVectorNode::make(C, opc, ctl, mem, adr, atyp, vlen, velt_basic_type(n));
1380         vlen_in_bytes = vn->as_LoadVector()->memory_size();
1381       } else if (n->is_Store()) {
1382         // Promote value to be stored to vector
1383         Node* val = vector_opd(p, MemNode::ValueIn);
1384         Node* ctl = n->in(MemNode::Control);
1385         Node* mem = first->in(MemNode::Memory);
1386         Node* adr = low_adr->in(MemNode::Address);
1387         const TypePtr* atyp = n->adr_type();
1388         vn = StoreVectorNode::make(C, opc, ctl, mem, adr, atyp, val, vlen);
1389         vlen_in_bytes = vn->as_StoreVector()->memory_size();
1390       } else if (n->req() == 3) {
1391         // Promote operands to vector
1392         Node* in1 = vector_opd(p, 1);
1393         Node* in2 = vector_opd(p, 2);
1394         if (VectorNode::is_invariant_vector(in1) && (n->is_Add() || n->is_Mul())) {
1395           // Move invariant vector input into second position to avoid register spilling.
1396           Node* tmp = in1;
1397           in1 = in2;
1398           in2 = tmp;
1399         }
1400         vn = VectorNode::make(C, opc, in1, in2, vlen, velt_basic_type(n));
1401         vlen_in_bytes = vn->as_Vector()->length_in_bytes();
1402       } else {
1403         ShouldNotReachHere();
1404       }
1405       assert(vn != NULL, "sanity");
1406       _igvn.register_new_node_with_optimizer(vn);
1407       _phase->set_ctrl(vn, _phase->get_ctrl(p->at(0)));
1408       for (uint j = 0; j < p->size(); j++) {
1409         Node* pm = p->at(j);
1410         _igvn.replace_node(pm, vn);
1411       }
1412       _igvn._worklist.push(vn);
1413 
1414       if (vlen_in_bytes > max_vlen_in_bytes) {
1415         max_vlen_in_bytes = vlen_in_bytes;
1416       }
1417 #ifdef ASSERT
1418       if (TraceNewVectors) {
1419         tty->print("new Vector node: ");
1420         vn->dump();
1421       }
1422 #endif
1423     }
1424   }
1425   C->set_max_vector_size(max_vlen_in_bytes);
1426 }
1427 
1428 //------------------------------vector_opd---------------------------
1429 // Create a vector operand for the nodes in pack p for operand: in(opd_idx)
1430 Node* SuperWord::vector_opd(Node_List* p, int opd_idx) {
1431   Node* p0 = p->at(0);
1432   uint vlen = p->size();
1433   Node* opd = p0->in(opd_idx);
1434 
1435   if (same_inputs(p, opd_idx)) {
1436     if (opd->is_Vector() || opd->is_LoadVector()) {
1437       assert(((opd_idx != 2) || !VectorNode::is_shift(p0)), "shift's count can't be vector");
1438       return opd; // input is matching vector
1439     }
1440     if ((opd_idx == 2) && VectorNode::is_shift(p0)) {
1441       Compile* C = _phase->C;
1442       Node* cnt = opd;
1443       // Vector instructions do not mask shift count, do it here.
1444       juint mask = (p0->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1);
1445       const TypeInt* t = opd->find_int_type();
1446       if (t != NULL && t->is_con()) {
1447         juint shift = t->get_con();
1448         if (shift > mask) { // Unsigned cmp
1449           cnt = ConNode::make(C, TypeInt::make(shift & mask));
1450         }
1451       } else {
1452         if (t == NULL || t->_lo < 0 || t->_hi > (int)mask) {
1453           cnt = ConNode::make(C, TypeInt::make(mask));
1454           _igvn.register_new_node_with_optimizer(cnt);
1455           cnt = new (C) AndINode(opd, cnt);
1456           _igvn.register_new_node_with_optimizer(cnt);
1457           _phase->set_ctrl(cnt, _phase->get_ctrl(opd));
1458         }
1459         assert(opd->bottom_type()->isa_int(), "int type only");
1460         // Move non constant shift count into vector register.
1461         cnt = VectorNode::shift_count(C, p0, cnt, vlen, velt_basic_type(p0));
1462       }
1463       if (cnt != opd) {
1464         _igvn.register_new_node_with_optimizer(cnt);
1465         _phase->set_ctrl(cnt, _phase->get_ctrl(opd));
1466       }
1467       return cnt;
1468     }
1469     assert(!opd->is_StoreVector(), "such vector is not expected here");
1470     // Convert scalar input to vector with the same number of elements as
1471     // p0's vector. Use p0's type because size of operand's container in
1472     // vector should match p0's size regardless operand's size.
1473     const Type* p0_t = velt_type(p0);
1474     VectorNode* vn = VectorNode::scalar2vector(_phase->C, opd, vlen, p0_t);
1475 
1476     _igvn.register_new_node_with_optimizer(vn);
1477     _phase->set_ctrl(vn, _phase->get_ctrl(opd));
1478 #ifdef ASSERT
1479     if (TraceNewVectors) {
1480       tty->print("new Vector node: ");
1481       vn->dump();
1482     }
1483 #endif
1484     return vn;
1485   }
1486 
1487   // Insert pack operation
1488   BasicType bt = velt_basic_type(p0);
1489   PackNode* pk = PackNode::make(_phase->C, opd, vlen, bt);
1490   DEBUG_ONLY( const BasicType opd_bt = opd->bottom_type()->basic_type(); )
1491 
1492   for (uint i = 1; i < vlen; i++) {
1493     Node* pi = p->at(i);
1494     Node* in = pi->in(opd_idx);
1495     assert(my_pack(in) == NULL, "Should already have been unpacked");
1496     assert(opd_bt == in->bottom_type()->basic_type(), "all same type");
1497     pk->add_opd(in);
1498   }
1499   _igvn.register_new_node_with_optimizer(pk);
1500   _phase->set_ctrl(pk, _phase->get_ctrl(opd));
1501 #ifdef ASSERT
1502   if (TraceNewVectors) {
1503     tty->print("new Vector node: ");
1504     pk->dump();
1505   }
1506 #endif
1507   return pk;
1508 }
1509 
1510 //------------------------------insert_extracts---------------------------
1511 // If a use of pack p is not a vector use, then replace the
1512 // use with an extract operation.
1513 void SuperWord::insert_extracts(Node_List* p) {
1514   if (p->at(0)->is_Store()) return;
1515   assert(_n_idx_list.is_empty(), "empty (node,index) list");
1516 
1517   // Inspect each use of each pack member.  For each use that is
1518   // not a vector use, replace the use with an extract operation.
1519 
1520   for (uint i = 0; i < p->size(); i++) {
1521     Node* def = p->at(i);
1522     for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
1523       Node* use = def->fast_out(j);
1524       for (uint k = 0; k < use->req(); k++) {
1525         Node* n = use->in(k);
1526         if (def == n) {
1527           if (!is_vector_use(use, k)) {
1528             _n_idx_list.push(use, k);
1529           }
1530         }
1531       }
1532     }
1533   }
1534 
1535   while (_n_idx_list.is_nonempty()) {
1536     Node* use = _n_idx_list.node();
1537     int   idx = _n_idx_list.index();
1538     _n_idx_list.pop();
1539     Node* def = use->in(idx);
1540 
1541     // Insert extract operation
1542     _igvn.hash_delete(def);
1543     int def_pos = alignment(def) / data_size(def);
1544 
1545     Node* ex = ExtractNode::make(_phase->C, def, def_pos, velt_basic_type(def));
1546     _igvn.register_new_node_with_optimizer(ex);
1547     _phase->set_ctrl(ex, _phase->get_ctrl(def));
1548     _igvn.replace_input_of(use, idx, ex);
1549     _igvn._worklist.push(def);
1550 
1551     bb_insert_after(ex, bb_idx(def));
1552     set_velt_type(ex, velt_type(def));
1553   }
1554 }
1555 
1556 //------------------------------is_vector_use---------------------------
1557 // Is use->in(u_idx) a vector use?
1558 bool SuperWord::is_vector_use(Node* use, int u_idx) {
1559   Node_List* u_pk = my_pack(use);
1560   if (u_pk == NULL) return false;
1561   Node* def = use->in(u_idx);
1562   Node_List* d_pk = my_pack(def);
1563   if (d_pk == NULL) {
1564     // check for scalar promotion
1565     Node* n = u_pk->at(0)->in(u_idx);
1566     for (uint i = 1; i < u_pk->size(); i++) {
1567       if (u_pk->at(i)->in(u_idx) != n) return false;
1568     }
1569     return true;
1570   }
1571   if (u_pk->size() != d_pk->size())
1572     return false;
1573   for (uint i = 0; i < u_pk->size(); i++) {
1574     Node* ui = u_pk->at(i);
1575     Node* di = d_pk->at(i);
1576     if (ui->in(u_idx) != di || alignment(ui) != alignment(di))
1577       return false;
1578   }
1579   return true;
1580 }
1581 
1582 //------------------------------construct_bb---------------------------
1583 // Construct reverse postorder list of block members
1584 bool SuperWord::construct_bb() {
1585   Node* entry = bb();
1586 
1587   assert(_stk.length() == 0,            "stk is empty");
1588   assert(_block.length() == 0,          "block is empty");
1589   assert(_data_entry.length() == 0,     "data_entry is empty");
1590   assert(_mem_slice_head.length() == 0, "mem_slice_head is empty");
1591   assert(_mem_slice_tail.length() == 0, "mem_slice_tail is empty");
1592 
1593   // Find non-control nodes with no inputs from within block,
1594   // create a temporary map from node _idx to bb_idx for use
1595   // by the visited and post_visited sets,
1596   // and count number of nodes in block.
1597   int bb_ct = 0;
1598   for (uint i = 0; i < lpt()->_body.size(); i++ ) {
1599     Node *n = lpt()->_body.at(i);
1600     set_bb_idx(n, i); // Create a temporary map
1601     if (in_bb(n)) {
1602       if (n->is_LoadStore() || n->is_MergeMem() ||
1603           (n->is_Proj() && !n->as_Proj()->is_CFG())) {
1604         // Bailout if the loop has LoadStore, MergeMem or data Proj
1605         // nodes. Superword optimization does not work with them.
1606         return false;
1607       }
1608       bb_ct++;
1609       if (!n->is_CFG()) {
1610         bool found = false;
1611         for (uint j = 0; j < n->req(); j++) {
1612           Node* def = n->in(j);
1613           if (def && in_bb(def)) {
1614             found = true;
1615             break;
1616           }
1617         }
1618         if (!found) {
1619           assert(n != entry, "can't be entry");
1620           _data_entry.push(n);
1621         }
1622       }
1623     }
1624   }
1625 
1626   // Find memory slices (head and tail)
1627   for (DUIterator_Fast imax, i = lp()->fast_outs(imax); i < imax; i++) {
1628     Node *n = lp()->fast_out(i);
1629     if (in_bb(n) && (n->is_Phi() && n->bottom_type() == Type::MEMORY)) {
1630       Node* n_tail  = n->in(LoopNode::LoopBackControl);
1631       if (n_tail != n->in(LoopNode::EntryControl)) {
1632         if (!n_tail->is_Mem()) {
1633           assert(n_tail->is_Mem(), err_msg_res("unexpected node for memory slice: %s", n_tail->Name()));
1634           return false; // Bailout
1635         }
1636         _mem_slice_head.push(n);
1637         _mem_slice_tail.push(n_tail);
1638       }
1639     }
1640   }
1641 
1642   // Create an RPO list of nodes in block
1643 
1644   visited_clear();
1645   post_visited_clear();
1646 
1647   // Push all non-control nodes with no inputs from within block, then control entry
1648   for (int j = 0; j < _data_entry.length(); j++) {
1649     Node* n = _data_entry.at(j);
1650     visited_set(n);
1651     _stk.push(n);
1652   }
1653   visited_set(entry);
1654   _stk.push(entry);
1655 
1656   // Do a depth first walk over out edges
1657   int rpo_idx = bb_ct - 1;
1658   int size;
1659   while ((size = _stk.length()) > 0) {
1660     Node* n = _stk.top(); // Leave node on stack
1661     if (!visited_test_set(n)) {
1662       // forward arc in graph
1663     } else if (!post_visited_test(n)) {
1664       // cross or back arc
1665       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1666         Node *use = n->fast_out(i);
1667         if (in_bb(use) && !visited_test(use) &&
1668             // Don't go around backedge
1669             (!use->is_Phi() || n == entry)) {
1670           _stk.push(use);
1671         }
1672       }
1673       if (_stk.length() == size) {
1674         // There were no additional uses, post visit node now
1675         _stk.pop(); // Remove node from stack
1676         assert(rpo_idx >= 0, "");
1677         _block.at_put_grow(rpo_idx, n);
1678         rpo_idx--;
1679         post_visited_set(n);
1680         assert(rpo_idx >= 0 || _stk.is_empty(), "");
1681       }
1682     } else {
1683       _stk.pop(); // Remove post-visited node from stack
1684     }
1685   }
1686 
1687   // Create real map of block indices for nodes
1688   for (int j = 0; j < _block.length(); j++) {
1689     Node* n = _block.at(j);
1690     set_bb_idx(n, j);
1691   }
1692 
1693   initialize_bb(); // Ensure extra info is allocated.
1694 
1695 #ifndef PRODUCT
1696   if (TraceSuperWord) {
1697     print_bb();
1698     tty->print_cr("\ndata entry nodes: %s", _data_entry.length() > 0 ? "" : "NONE");
1699     for (int m = 0; m < _data_entry.length(); m++) {
1700       tty->print("%3d ", m);
1701       _data_entry.at(m)->dump();
1702     }
1703     tty->print_cr("\nmemory slices: %s", _mem_slice_head.length() > 0 ? "" : "NONE");
1704     for (int m = 0; m < _mem_slice_head.length(); m++) {
1705       tty->print("%3d ", m); _mem_slice_head.at(m)->dump();
1706       tty->print("    ");    _mem_slice_tail.at(m)->dump();
1707     }
1708   }
1709 #endif
1710   assert(rpo_idx == -1 && bb_ct == _block.length(), "all block members found");
1711   return (_mem_slice_head.length() > 0) || (_data_entry.length() > 0);
1712 }
1713 
1714 //------------------------------initialize_bb---------------------------
1715 // Initialize per node info
1716 void SuperWord::initialize_bb() {
1717   Node* last = _block.at(_block.length() - 1);
1718   grow_node_info(bb_idx(last));
1719 }
1720 
1721 //------------------------------bb_insert_after---------------------------
1722 // Insert n into block after pos
1723 void SuperWord::bb_insert_after(Node* n, int pos) {
1724   int n_pos = pos + 1;
1725   // Make room
1726   for (int i = _block.length() - 1; i >= n_pos; i--) {
1727     _block.at_put_grow(i+1, _block.at(i));
1728   }
1729   for (int j = _node_info.length() - 1; j >= n_pos; j--) {
1730     _node_info.at_put_grow(j+1, _node_info.at(j));
1731   }
1732   // Set value
1733   _block.at_put_grow(n_pos, n);
1734   _node_info.at_put_grow(n_pos, SWNodeInfo::initial);
1735   // Adjust map from node->_idx to _block index
1736   for (int i = n_pos; i < _block.length(); i++) {
1737     set_bb_idx(_block.at(i), i);
1738   }
1739 }
1740 
1741 //------------------------------compute_max_depth---------------------------
1742 // Compute max depth for expressions from beginning of block
1743 // Use to prune search paths during test for independence.
1744 void SuperWord::compute_max_depth() {
1745   int ct = 0;
1746   bool again;
1747   do {
1748     again = false;
1749     for (int i = 0; i < _block.length(); i++) {
1750       Node* n = _block.at(i);
1751       if (!n->is_Phi()) {
1752         int d_orig = depth(n);
1753         int d_in   = 0;
1754         for (DepPreds preds(n, _dg); !preds.done(); preds.next()) {
1755           Node* pred = preds.current();
1756           if (in_bb(pred)) {
1757             d_in = MAX2(d_in, depth(pred));
1758           }
1759         }
1760         if (d_in + 1 != d_orig) {
1761           set_depth(n, d_in + 1);
1762           again = true;
1763         }
1764       }
1765     }
1766     ct++;
1767   } while (again);
1768 #ifndef PRODUCT
1769   if (TraceSuperWord && Verbose)
1770     tty->print_cr("compute_max_depth iterated: %d times", ct);
1771 #endif
1772 }
1773 
1774 //-------------------------compute_vector_element_type-----------------------
1775 // Compute necessary vector element type for expressions
1776 // This propagates backwards a narrower integer type when the
1777 // upper bits of the value are not needed.
1778 // Example:  char a,b,c;  a = b + c;
1779 // Normally the type of the add is integer, but for packed character
1780 // operations the type of the add needs to be char.
1781 void SuperWord::compute_vector_element_type() {
1782 #ifndef PRODUCT
1783   if (TraceSuperWord && Verbose)
1784     tty->print_cr("\ncompute_velt_type:");
1785 #endif
1786 
1787   // Initial type
1788   for (int i = 0; i < _block.length(); i++) {
1789     Node* n = _block.at(i);
1790     set_velt_type(n, container_type(n));
1791   }
1792 
1793   // Propagate integer narrowed type backwards through operations
1794   // that don't depend on higher order bits
1795   for (int i = _block.length() - 1; i >= 0; i--) {
1796     Node* n = _block.at(i);
1797     // Only integer types need be examined
1798     const Type* vtn = velt_type(n);
1799     if (vtn->basic_type() == T_INT) {
1800       uint start, end;
1801       VectorNode::vector_operands(n, &start, &end);
1802 
1803       for (uint j = start; j < end; j++) {
1804         Node* in  = n->in(j);
1805         // Don't propagate through a memory
1806         if (!in->is_Mem() && in_bb(in) && velt_type(in)->basic_type() == T_INT &&
1807             data_size(n) < data_size(in)) {
1808           bool same_type = true;
1809           for (DUIterator_Fast kmax, k = in->fast_outs(kmax); k < kmax; k++) {
1810             Node *use = in->fast_out(k);
1811             if (!in_bb(use) || !same_velt_type(use, n)) {
1812               same_type = false;
1813               break;
1814             }
1815           }
1816           if (same_type) {
1817             // For right shifts of small integer types (bool, byte, char, short)
1818             // we need precise information about sign-ness. Only Load nodes have
1819             // this information because Store nodes are the same for signed and
1820             // unsigned values. And any arithmetic operation after a load may
1821             // expand a value to signed Int so such right shifts can't be used
1822             // because vector elements do not have upper bits of Int.
1823             const Type* vt = vtn;
1824             if (VectorNode::is_shift(in)) {
1825               Node* load = in->in(1);
1826               if (load->is_Load() && in_bb(load) && (velt_type(load)->basic_type() == T_INT)) {
1827                 vt = velt_type(load);
1828               } else if (in->Opcode() != Op_LShiftI) {
1829                 // Widen type to Int to avoid creation of right shift vector
1830                 // (align + data_size(s1) check in stmts_can_pack() will fail).
1831                 // Note, left shifts work regardless type.
1832                 vt = TypeInt::INT;
1833               }
1834             }
1835             set_velt_type(in, vt);
1836           }
1837         }
1838       }
1839     }
1840   }
1841 #ifndef PRODUCT
1842   if (TraceSuperWord && Verbose) {
1843     for (int i = 0; i < _block.length(); i++) {
1844       Node* n = _block.at(i);
1845       velt_type(n)->dump();
1846       tty->print("\t");
1847       n->dump();
1848     }
1849   }
1850 #endif
1851 }
1852 
1853 //------------------------------memory_alignment---------------------------
1854 // Alignment within a vector memory reference
1855 int SuperWord::memory_alignment(MemNode* s, int iv_adjust) {
1856   SWPointer p(s, this);
1857   if (!p.valid()) {
1858     return bottom_align;
1859   }
1860   int vw = vector_width_in_bytes(s);
1861   if (vw < 2) {
1862     return bottom_align; // No vectors for this type
1863   }
1864   int offset  = p.offset_in_bytes();
1865   offset     += iv_adjust*p.memory_size();
1866   int off_rem = offset % vw;
1867   int off_mod = off_rem >= 0 ? off_rem : off_rem + vw;
1868   return off_mod;
1869 }
1870 
1871 //---------------------------container_type---------------------------
1872 // Smallest type containing range of values
1873 const Type* SuperWord::container_type(Node* n) {
1874   if (n->is_Mem()) {
1875     BasicType bt = n->as_Mem()->memory_type();
1876     if (n->is_Store() && (bt == T_CHAR)) {
1877       // Use T_SHORT type instead of T_CHAR for stored values because any
1878       // preceding arithmetic operation extends values to signed Int.
1879       bt = T_SHORT;
1880     }
1881     if (n->Opcode() == Op_LoadUB) {
1882       // Adjust type for unsigned byte loads, it is important for right shifts.
1883       // T_BOOLEAN is used because there is no basic type representing type
1884       // TypeInt::UBYTE. Use of T_BOOLEAN for vectors is fine because only
1885       // size (one byte) and sign is important.
1886       bt = T_BOOLEAN;
1887     }
1888     return Type::get_const_basic_type(bt);
1889   }
1890   const Type* t = _igvn.type(n);
1891   if (t->basic_type() == T_INT) {
1892     // A narrow type of arithmetic operations will be determined by
1893     // propagating the type of memory operations.
1894     return TypeInt::INT;
1895   }
1896   return t;
1897 }
1898 
1899 bool SuperWord::same_velt_type(Node* n1, Node* n2) {
1900   const Type* vt1 = velt_type(n1);
1901   const Type* vt2 = velt_type(n2);
1902   if (vt1->basic_type() == T_INT && vt2->basic_type() == T_INT) {
1903     // Compare vectors element sizes for integer types.
1904     return data_size(n1) == data_size(n2);
1905   }
1906   return vt1 == vt2;
1907 }
1908 
1909 //------------------------------in_packset---------------------------
1910 // Are s1 and s2 in a pack pair and ordered as s1,s2?
1911 bool SuperWord::in_packset(Node* s1, Node* s2) {
1912   for (int i = 0; i < _packset.length(); i++) {
1913     Node_List* p = _packset.at(i);
1914     assert(p->size() == 2, "must be");
1915     if (p->at(0) == s1 && p->at(p->size()-1) == s2) {
1916       return true;
1917     }
1918   }
1919   return false;
1920 }
1921 
1922 //------------------------------in_pack---------------------------
1923 // Is s in pack p?
1924 Node_List* SuperWord::in_pack(Node* s, Node_List* p) {
1925   for (uint i = 0; i < p->size(); i++) {
1926     if (p->at(i) == s) {
1927       return p;
1928     }
1929   }
1930   return NULL;
1931 }
1932 
1933 //------------------------------remove_pack_at---------------------------
1934 // Remove the pack at position pos in the packset
1935 void SuperWord::remove_pack_at(int pos) {
1936   Node_List* p = _packset.at(pos);
1937   for (uint i = 0; i < p->size(); i++) {
1938     Node* s = p->at(i);
1939     set_my_pack(s, NULL);
1940   }
1941   _packset.remove_at(pos);
1942 }
1943 
1944 //------------------------------executed_first---------------------------
1945 // Return the node executed first in pack p.  Uses the RPO block list
1946 // to determine order.
1947 Node* SuperWord::executed_first(Node_List* p) {
1948   Node* n = p->at(0);
1949   int n_rpo = bb_idx(n);
1950   for (uint i = 1; i < p->size(); i++) {
1951     Node* s = p->at(i);
1952     int s_rpo = bb_idx(s);
1953     if (s_rpo < n_rpo) {
1954       n = s;
1955       n_rpo = s_rpo;
1956     }
1957   }
1958   return n;
1959 }
1960 
1961 //------------------------------executed_last---------------------------
1962 // Return the node executed last in pack p.
1963 Node* SuperWord::executed_last(Node_List* p) {
1964   Node* n = p->at(0);
1965   int n_rpo = bb_idx(n);
1966   for (uint i = 1; i < p->size(); i++) {
1967     Node* s = p->at(i);
1968     int s_rpo = bb_idx(s);
1969     if (s_rpo > n_rpo) {
1970       n = s;
1971       n_rpo = s_rpo;
1972     }
1973   }
1974   return n;
1975 }
1976 
1977 //----------------------------align_initial_loop_index---------------------------
1978 // Adjust pre-loop limit so that in main loop, a load/store reference
1979 // to align_to_ref will be a position zero in the vector.
1980 //   (iv + k) mod vector_align == 0
1981 void SuperWord::align_initial_loop_index(MemNode* align_to_ref) {
1982   CountedLoopNode *main_head = lp()->as_CountedLoop();
1983   assert(main_head->is_main_loop(), "");
1984   CountedLoopEndNode* pre_end = get_pre_loop_end(main_head);
1985   assert(pre_end != NULL, "we must have a correct pre-loop");
1986   Node *pre_opaq1 = pre_end->limit();
1987   assert(pre_opaq1->Opcode() == Op_Opaque1, "");
1988   Opaque1Node *pre_opaq = (Opaque1Node*)pre_opaq1;
1989   Node *lim0 = pre_opaq->in(1);
1990 
1991   // Where we put new limit calculations
1992   Node *pre_ctrl = pre_end->loopnode()->in(LoopNode::EntryControl);
1993 
1994   // Ensure the original loop limit is available from the
1995   // pre-loop Opaque1 node.
1996   Node *orig_limit = pre_opaq->original_loop_limit();
1997   assert(orig_limit != NULL && _igvn.type(orig_limit) != Type::TOP, "");
1998 
1999   SWPointer align_to_ref_p(align_to_ref, this);
2000   assert(align_to_ref_p.valid(), "sanity");
2001 
2002   // Given:
2003   //     lim0 == original pre loop limit
2004   //     V == v_align (power of 2)
2005   //     invar == extra invariant piece of the address expression
2006   //     e == offset [ +/- invar ]
2007   //
2008   // When reassociating expressions involving '%' the basic rules are:
2009   //     (a - b) % k == 0   =>  a % k == b % k
2010   // and:
2011   //     (a + b) % k == 0   =>  a % k == (k - b) % k
2012   //
2013   // For stride > 0 && scale > 0,
2014   //   Derive the new pre-loop limit "lim" such that the two constraints:
2015   //     (1) lim = lim0 + N           (where N is some positive integer < V)
2016   //     (2) (e + lim) % V == 0
2017   //   are true.
2018   //
2019   //   Substituting (1) into (2),
2020   //     (e + lim0 + N) % V == 0
2021   //   solve for N:
2022   //     N = (V - (e + lim0)) % V
2023   //   substitute back into (1), so that new limit
2024   //     lim = lim0 + (V - (e + lim0)) % V
2025   //
2026   // For stride > 0 && scale < 0
2027   //   Constraints:
2028   //     lim = lim0 + N
2029   //     (e - lim) % V == 0
2030   //   Solving for lim:
2031   //     (e - lim0 - N) % V == 0
2032   //     N = (e - lim0) % V
2033   //     lim = lim0 + (e - lim0) % V
2034   //
2035   // For stride < 0 && scale > 0
2036   //   Constraints:
2037   //     lim = lim0 - N
2038   //     (e + lim) % V == 0
2039   //   Solving for lim:
2040   //     (e + lim0 - N) % V == 0
2041   //     N = (e + lim0) % V
2042   //     lim = lim0 - (e + lim0) % V
2043   //
2044   // For stride < 0 && scale < 0
2045   //   Constraints:
2046   //     lim = lim0 - N
2047   //     (e - lim) % V == 0
2048   //   Solving for lim:
2049   //     (e - lim0 + N) % V == 0
2050   //     N = (V - (e - lim0)) % V
2051   //     lim = lim0 - (V - (e - lim0)) % V
2052 
2053   int vw = vector_width_in_bytes(align_to_ref);
2054   int stride   = iv_stride();
2055   int scale    = align_to_ref_p.scale_in_bytes();
2056   int elt_size = align_to_ref_p.memory_size();
2057   int v_align  = vw / elt_size;
2058   assert(v_align > 1, "sanity");
2059   int offset   = align_to_ref_p.offset_in_bytes() / elt_size;
2060   Node *offsn  = _igvn.intcon(offset);
2061 
2062   Node *e = offsn;
2063   if (align_to_ref_p.invar() != NULL) {
2064     // incorporate any extra invariant piece producing (offset +/- invar) >>> log2(elt)
2065     Node* log2_elt = _igvn.intcon(exact_log2(elt_size));
2066     Node* aref     = new (_phase->C) URShiftINode(align_to_ref_p.invar(), log2_elt);
2067     _igvn.register_new_node_with_optimizer(aref);
2068     _phase->set_ctrl(aref, pre_ctrl);
2069     if (align_to_ref_p.negate_invar()) {
2070       e = new (_phase->C) SubINode(e, aref);
2071     } else {
2072       e = new (_phase->C) AddINode(e, aref);
2073     }
2074     _igvn.register_new_node_with_optimizer(e);
2075     _phase->set_ctrl(e, pre_ctrl);
2076   }
2077   if (vw > ObjectAlignmentInBytes) {
2078     // incorporate base e +/- base && Mask >>> log2(elt)
2079     Node* xbase = new(_phase->C) CastP2XNode(NULL, align_to_ref_p.base());
2080     _igvn.register_new_node_with_optimizer(xbase);
2081 #ifdef _LP64
2082     xbase  = new (_phase->C) ConvL2INode(xbase);
2083     _igvn.register_new_node_with_optimizer(xbase);
2084 #endif
2085     Node* mask = _igvn.intcon(vw-1);
2086     Node* masked_xbase  = new (_phase->C) AndINode(xbase, mask);
2087     _igvn.register_new_node_with_optimizer(masked_xbase);
2088     Node* log2_elt = _igvn.intcon(exact_log2(elt_size));
2089     Node* bref     = new (_phase->C) URShiftINode(masked_xbase, log2_elt);
2090     _igvn.register_new_node_with_optimizer(bref);
2091     _phase->set_ctrl(bref, pre_ctrl);
2092     e = new (_phase->C) AddINode(e, bref);
2093     _igvn.register_new_node_with_optimizer(e);
2094     _phase->set_ctrl(e, pre_ctrl);
2095   }
2096 
2097   // compute e +/- lim0
2098   if (scale < 0) {
2099     e = new (_phase->C) SubINode(e, lim0);
2100   } else {
2101     e = new (_phase->C) AddINode(e, lim0);
2102   }
2103   _igvn.register_new_node_with_optimizer(e);
2104   _phase->set_ctrl(e, pre_ctrl);
2105 
2106   if (stride * scale > 0) {
2107     // compute V - (e +/- lim0)
2108     Node* va  = _igvn.intcon(v_align);
2109     e = new (_phase->C) SubINode(va, e);
2110     _igvn.register_new_node_with_optimizer(e);
2111     _phase->set_ctrl(e, pre_ctrl);
2112   }
2113   // compute N = (exp) % V
2114   Node* va_msk = _igvn.intcon(v_align - 1);
2115   Node* N = new (_phase->C) AndINode(e, va_msk);
2116   _igvn.register_new_node_with_optimizer(N);
2117   _phase->set_ctrl(N, pre_ctrl);
2118 
2119   //   substitute back into (1), so that new limit
2120   //     lim = lim0 + N
2121   Node* lim;
2122   if (stride < 0) {
2123     lim = new (_phase->C) SubINode(lim0, N);
2124   } else {
2125     lim = new (_phase->C) AddINode(lim0, N);
2126   }
2127   _igvn.register_new_node_with_optimizer(lim);
2128   _phase->set_ctrl(lim, pre_ctrl);
2129   Node* constrained =
2130     (stride > 0) ? (Node*) new (_phase->C) MinINode(lim, orig_limit)
2131                  : (Node*) new (_phase->C) MaxINode(lim, orig_limit);
2132   _igvn.register_new_node_with_optimizer(constrained);
2133   _phase->set_ctrl(constrained, pre_ctrl);
2134   _igvn.hash_delete(pre_opaq);
2135   pre_opaq->set_req(1, constrained);
2136 }
2137 
2138 //----------------------------get_pre_loop_end---------------------------
2139 // Find pre loop end from main loop.  Returns null if none.
2140 CountedLoopEndNode* SuperWord::get_pre_loop_end(CountedLoopNode *cl) {
2141   Node *ctrl = cl->in(LoopNode::EntryControl);
2142   if (!ctrl->is_IfTrue() && !ctrl->is_IfFalse()) return NULL;
2143   Node *iffm = ctrl->in(0);
2144   if (!iffm->is_If()) return NULL;
2145   Node *p_f = iffm->in(0);
2146   if (!p_f->is_IfFalse()) return NULL;
2147   if (!p_f->in(0)->is_CountedLoopEnd()) return NULL;
2148   CountedLoopEndNode *pre_end = p_f->in(0)->as_CountedLoopEnd();
2149   CountedLoopNode* loop_node = pre_end->loopnode();
2150   if (loop_node == NULL || !loop_node->is_pre_loop()) return NULL;
2151   return pre_end;
2152 }
2153 
2154 
2155 //------------------------------init---------------------------
2156 void SuperWord::init() {
2157   _dg.init();
2158   _packset.clear();
2159   _disjoint_ptrs.clear();
2160   _block.clear();
2161   _data_entry.clear();
2162   _mem_slice_head.clear();
2163   _mem_slice_tail.clear();
2164   _node_info.clear();
2165   _align_to_ref = NULL;
2166   _lpt = NULL;
2167   _lp = NULL;
2168   _bb = NULL;
2169   _iv = NULL;
2170 }
2171 
2172 //------------------------------print_packset---------------------------
2173 void SuperWord::print_packset() {
2174 #ifndef PRODUCT
2175   tty->print_cr("packset");
2176   for (int i = 0; i < _packset.length(); i++) {
2177     tty->print_cr("Pack: %d", i);
2178     Node_List* p = _packset.at(i);
2179     print_pack(p);
2180   }
2181 #endif
2182 }
2183 
2184 //------------------------------print_pack---------------------------
2185 void SuperWord::print_pack(Node_List* p) {
2186   for (uint i = 0; i < p->size(); i++) {
2187     print_stmt(p->at(i));
2188   }
2189 }
2190 
2191 //------------------------------print_bb---------------------------
2192 void SuperWord::print_bb() {
2193 #ifndef PRODUCT
2194   tty->print_cr("\nBlock");
2195   for (int i = 0; i < _block.length(); i++) {
2196     Node* n = _block.at(i);
2197     tty->print("%d ", i);
2198     if (n) {
2199       n->dump();
2200     }
2201   }
2202 #endif
2203 }
2204 
2205 //------------------------------print_stmt---------------------------
2206 void SuperWord::print_stmt(Node* s) {
2207 #ifndef PRODUCT
2208   tty->print(" align: %d \t", alignment(s));
2209   s->dump();
2210 #endif
2211 }
2212 
2213 //------------------------------blank---------------------------
2214 char* SuperWord::blank(uint depth) {
2215   static char blanks[101];
2216   assert(depth < 101, "too deep");
2217   for (uint i = 0; i < depth; i++) blanks[i] = ' ';
2218   blanks[depth] = '\0';
2219   return blanks;
2220 }
2221 
2222 
2223 //==============================SWPointer===========================
2224 
2225 //----------------------------SWPointer------------------------
2226 SWPointer::SWPointer(MemNode* mem, SuperWord* slp) :
2227   _mem(mem), _slp(slp),  _base(NULL),  _adr(NULL),
2228   _scale(0), _offset(0), _invar(NULL), _negate_invar(false) {
2229 
2230   Node* adr = mem->in(MemNode::Address);
2231   if (!adr->is_AddP()) {
2232     assert(!valid(), "too complex");
2233     return;
2234   }
2235   // Match AddP(base, AddP(ptr, k*iv [+ invariant]), constant)
2236   Node* base = adr->in(AddPNode::Base);
2237   //unsafe reference could not be aligned appropriately without runtime checking
2238   if (base == NULL || base->bottom_type() == Type::TOP) {
2239     assert(!valid(), "unsafe access");
2240     return;
2241   }
2242   for (int i = 0; i < 3; i++) {
2243     if (!scaled_iv_plus_offset(adr->in(AddPNode::Offset))) {
2244       assert(!valid(), "too complex");
2245       return;
2246     }
2247     adr = adr->in(AddPNode::Address);
2248     if (base == adr || !adr->is_AddP()) {
2249       break; // stop looking at addp's
2250     }
2251   }
2252   _base = base;
2253   _adr  = adr;
2254   assert(valid(), "Usable");
2255 }
2256 
2257 // Following is used to create a temporary object during
2258 // the pattern match of an address expression.
2259 SWPointer::SWPointer(SWPointer* p) :
2260   _mem(p->_mem), _slp(p->_slp),  _base(NULL),  _adr(NULL),
2261   _scale(0), _offset(0), _invar(NULL), _negate_invar(false) {}
2262 
2263 //------------------------scaled_iv_plus_offset--------------------
2264 // Match: k*iv + offset
2265 // where: k is a constant that maybe zero, and
2266 //        offset is (k2 [+/- invariant]) where k2 maybe zero and invariant is optional
2267 bool SWPointer::scaled_iv_plus_offset(Node* n) {
2268   if (scaled_iv(n)) {
2269     return true;
2270   }
2271   if (offset_plus_k(n)) {
2272     return true;
2273   }
2274   int opc = n->Opcode();
2275   if (opc == Op_AddI) {
2276     if (scaled_iv(n->in(1)) && offset_plus_k(n->in(2))) {
2277       return true;
2278     }
2279     if (scaled_iv(n->in(2)) && offset_plus_k(n->in(1))) {
2280       return true;
2281     }
2282   } else if (opc == Op_SubI) {
2283     if (scaled_iv(n->in(1)) && offset_plus_k(n->in(2), true)) {
2284       return true;
2285     }
2286     if (scaled_iv(n->in(2)) && offset_plus_k(n->in(1))) {
2287       _scale *= -1;
2288       return true;
2289     }
2290   }
2291   return false;
2292 }
2293 
2294 //----------------------------scaled_iv------------------------
2295 // Match: k*iv where k is a constant that's not zero
2296 bool SWPointer::scaled_iv(Node* n) {
2297   if (_scale != 0) {
2298     return false;  // already found a scale
2299   }
2300   if (n == iv()) {
2301     _scale = 1;
2302     return true;
2303   }
2304   int opc = n->Opcode();
2305   if (opc == Op_MulI) {
2306     if (n->in(1) == iv() && n->in(2)->is_Con()) {
2307       _scale = n->in(2)->get_int();
2308       return true;
2309     } else if (n->in(2) == iv() && n->in(1)->is_Con()) {
2310       _scale = n->in(1)->get_int();
2311       return true;
2312     }
2313   } else if (opc == Op_LShiftI) {
2314     if (n->in(1) == iv() && n->in(2)->is_Con()) {
2315       _scale = 1 << n->in(2)->get_int();
2316       return true;
2317     }
2318   } else if (opc == Op_ConvI2L) {
2319     if (scaled_iv_plus_offset(n->in(1))) {
2320       return true;
2321     }
2322   } else if (opc == Op_LShiftL) {
2323     if (!has_iv() && _invar == NULL) {
2324       // Need to preserve the current _offset value, so
2325       // create a temporary object for this expression subtree.
2326       // Hacky, so should re-engineer the address pattern match.
2327       SWPointer tmp(this);
2328       if (tmp.scaled_iv_plus_offset(n->in(1))) {
2329         if (tmp._invar == NULL) {
2330           int mult = 1 << n->in(2)->get_int();
2331           _scale   = tmp._scale  * mult;
2332           _offset += tmp._offset * mult;
2333           return true;
2334         }
2335       }
2336     }
2337   }
2338   return false;
2339 }
2340 
2341 //----------------------------offset_plus_k------------------------
2342 // Match: offset is (k [+/- invariant])
2343 // where k maybe zero and invariant is optional, but not both.
2344 bool SWPointer::offset_plus_k(Node* n, bool negate) {
2345   int opc = n->Opcode();
2346   if (opc == Op_ConI) {
2347     _offset += negate ? -(n->get_int()) : n->get_int();
2348     return true;
2349   } else if (opc == Op_ConL) {
2350     // Okay if value fits into an int
2351     const TypeLong* t = n->find_long_type();
2352     if (t->higher_equal(TypeLong::INT)) {
2353       jlong loff = n->get_long();
2354       jint  off  = (jint)loff;
2355       _offset += negate ? -off : loff;
2356       return true;
2357     }
2358     return false;
2359   }
2360   if (_invar != NULL) return false; // already have an invariant
2361   if (opc == Op_AddI) {
2362     if (n->in(2)->is_Con() && invariant(n->in(1))) {
2363       _negate_invar = negate;
2364       _invar = n->in(1);
2365       _offset += negate ? -(n->in(2)->get_int()) : n->in(2)->get_int();
2366       return true;
2367     } else if (n->in(1)->is_Con() && invariant(n->in(2))) {
2368       _offset += negate ? -(n->in(1)->get_int()) : n->in(1)->get_int();
2369       _negate_invar = negate;
2370       _invar = n->in(2);
2371       return true;
2372     }
2373   }
2374   if (opc == Op_SubI) {
2375     if (n->in(2)->is_Con() && invariant(n->in(1))) {
2376       _negate_invar = negate;
2377       _invar = n->in(1);
2378       _offset += !negate ? -(n->in(2)->get_int()) : n->in(2)->get_int();
2379       return true;
2380     } else if (n->in(1)->is_Con() && invariant(n->in(2))) {
2381       _offset += negate ? -(n->in(1)->get_int()) : n->in(1)->get_int();
2382       _negate_invar = !negate;
2383       _invar = n->in(2);
2384       return true;
2385     }
2386   }
2387   if (invariant(n)) {
2388     _negate_invar = negate;
2389     _invar = n;
2390     return true;
2391   }
2392   return false;
2393 }
2394 
2395 //----------------------------print------------------------
2396 void SWPointer::print() {
2397 #ifndef PRODUCT
2398   tty->print("base: %d  adr: %d  scale: %d  offset: %d  invar: %c%d\n",
2399              _base != NULL ? _base->_idx : 0,
2400              _adr  != NULL ? _adr->_idx  : 0,
2401              _scale, _offset,
2402              _negate_invar?'-':'+',
2403              _invar != NULL ? _invar->_idx : 0);
2404 #endif
2405 }
2406 
2407 // ========================= OrderedPair =====================
2408 
2409 const OrderedPair OrderedPair::initial;
2410 
2411 // ========================= SWNodeInfo =====================
2412 
2413 const SWNodeInfo SWNodeInfo::initial;
2414 
2415 
2416 // ============================ DepGraph ===========================
2417 
2418 //------------------------------make_node---------------------------
2419 // Make a new dependence graph node for an ideal node.
2420 DepMem* DepGraph::make_node(Node* node) {
2421   DepMem* m = new (_arena) DepMem(node);
2422   if (node != NULL) {
2423     assert(_map.at_grow(node->_idx) == NULL, "one init only");
2424     _map.at_put_grow(node->_idx, m);
2425   }
2426   return m;
2427 }
2428 
2429 //------------------------------make_edge---------------------------
2430 // Make a new dependence graph edge from dpred -> dsucc
2431 DepEdge* DepGraph::make_edge(DepMem* dpred, DepMem* dsucc) {
2432   DepEdge* e = new (_arena) DepEdge(dpred, dsucc, dsucc->in_head(), dpred->out_head());
2433   dpred->set_out_head(e);
2434   dsucc->set_in_head(e);
2435   return e;
2436 }
2437 
2438 // ========================== DepMem ========================
2439 
2440 //------------------------------in_cnt---------------------------
2441 int DepMem::in_cnt() {
2442   int ct = 0;
2443   for (DepEdge* e = _in_head; e != NULL; e = e->next_in()) ct++;
2444   return ct;
2445 }
2446 
2447 //------------------------------out_cnt---------------------------
2448 int DepMem::out_cnt() {
2449   int ct = 0;
2450   for (DepEdge* e = _out_head; e != NULL; e = e->next_out()) ct++;
2451   return ct;
2452 }
2453 
2454 //------------------------------print-----------------------------
2455 void DepMem::print() {
2456 #ifndef PRODUCT
2457   tty->print("  DepNode %d (", _node->_idx);
2458   for (DepEdge* p = _in_head; p != NULL; p = p->next_in()) {
2459     Node* pred = p->pred()->node();
2460     tty->print(" %d", pred != NULL ? pred->_idx : 0);
2461   }
2462   tty->print(") [");
2463   for (DepEdge* s = _out_head; s != NULL; s = s->next_out()) {
2464     Node* succ = s->succ()->node();
2465     tty->print(" %d", succ != NULL ? succ->_idx : 0);
2466   }
2467   tty->print_cr(" ]");
2468 #endif
2469 }
2470 
2471 // =========================== DepEdge =========================
2472 
2473 //------------------------------DepPreds---------------------------
2474 void DepEdge::print() {
2475 #ifndef PRODUCT
2476   tty->print_cr("DepEdge: %d [ %d ]", _pred->node()->_idx, _succ->node()->_idx);
2477 #endif
2478 }
2479 
2480 // =========================== DepPreds =========================
2481 // Iterator over predecessor edges in the dependence graph.
2482 
2483 //------------------------------DepPreds---------------------------
2484 DepPreds::DepPreds(Node* n, DepGraph& dg) {
2485   _n = n;
2486   _done = false;
2487   if (_n->is_Store() || _n->is_Load()) {
2488     _next_idx = MemNode::Address;
2489     _end_idx  = n->req();
2490     _dep_next = dg.dep(_n)->in_head();
2491   } else if (_n->is_Mem()) {
2492     _next_idx = 0;
2493     _end_idx  = 0;
2494     _dep_next = dg.dep(_n)->in_head();
2495   } else {
2496     _next_idx = 1;
2497     _end_idx  = _n->req();
2498     _dep_next = NULL;
2499   }
2500   next();
2501 }
2502 
2503 //------------------------------next---------------------------
2504 void DepPreds::next() {
2505   if (_dep_next != NULL) {
2506     _current  = _dep_next->pred()->node();
2507     _dep_next = _dep_next->next_in();
2508   } else if (_next_idx < _end_idx) {
2509     _current  = _n->in(_next_idx++);
2510   } else {
2511     _done = true;
2512   }
2513 }
2514 
2515 // =========================== DepSuccs =========================
2516 // Iterator over successor edges in the dependence graph.
2517 
2518 //------------------------------DepSuccs---------------------------
2519 DepSuccs::DepSuccs(Node* n, DepGraph& dg) {
2520   _n = n;
2521   _done = false;
2522   if (_n->is_Load()) {
2523     _next_idx = 0;
2524     _end_idx  = _n->outcnt();
2525     _dep_next = dg.dep(_n)->out_head();
2526   } else if (_n->is_Mem() || _n->is_Phi() && _n->bottom_type() == Type::MEMORY) {
2527     _next_idx = 0;
2528     _end_idx  = 0;
2529     _dep_next = dg.dep(_n)->out_head();
2530   } else {
2531     _next_idx = 0;
2532     _end_idx  = _n->outcnt();
2533     _dep_next = NULL;
2534   }
2535   next();
2536 }
2537 
2538 //-------------------------------next---------------------------
2539 void DepSuccs::next() {
2540   if (_dep_next != NULL) {
2541     _current  = _dep_next->succ()->node();
2542     _dep_next = _dep_next->next_out();
2543   } else if (_next_idx < _end_idx) {
2544     _current  = _n->raw_out(_next_idx++);
2545   } else {
2546     _done = true;
2547   }
2548 }