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