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