1 /*
   2  * Copyright (c) 2007, 2020, 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 "memory/resourceArea.hpp"
  29 #include "opto/addnode.hpp"
  30 #include "opto/callnode.hpp"
  31 #include "opto/castnode.hpp"
  32 #include "opto/convertnode.hpp"
  33 #include "opto/divnode.hpp"
  34 #include "opto/matcher.hpp"
  35 #include "opto/memnode.hpp"
  36 #include "opto/mulnode.hpp"
  37 #include "opto/opcodes.hpp"
  38 #include "opto/opaquenode.hpp"
  39 #include "opto/superword.hpp"
  40 #include "opto/vectornode.hpp"
  41 #include "opto/movenode.hpp"
  42 #include "utilities/powerOfTwo.hpp"
  43 
  44 //
  45 //                  S U P E R W O R D   T R A N S F O R M
  46 //=============================================================================
  47 
  48 //------------------------------SuperWord---------------------------
  49 SuperWord::SuperWord(PhaseIdealLoop* phase) :
  50   _phase(phase),
  51   _arena(phase->C->comp_arena()),
  52   _igvn(phase->_igvn),
  53   _packset(arena(), 8,  0, NULL),         // packs for the current block
  54   _bb_idx(arena(), (int)(1.10 * phase->C->unique()), 0, 0), // node idx to index in bb
  55   _block(arena(), 8,  0, NULL),           // nodes in current block
  56   _post_block(arena(), 8, 0, NULL),       // nodes common to current block which are marked as post loop vectorizable
  57   _data_entry(arena(), 8,  0, NULL),      // nodes with all inputs from outside
  58   _mem_slice_head(arena(), 8,  0, NULL),  // memory slice heads
  59   _mem_slice_tail(arena(), 8,  0, NULL),  // memory slice tails
  60   _node_info(arena(), 8,  0, SWNodeInfo::initial), // info needed per node
  61   _clone_map(phase->C->clone_map()),      // map of nodes created in cloning
  62   _cmovev_kit(_arena, this),              // map to facilitate CMoveV creation
  63   _align_to_ref(NULL),                    // memory reference to align vectors to
  64   _disjoint_ptrs(arena(), 8,  0, OrderedPair::initial), // runtime disambiguated pointer pairs
  65   _dg(_arena),                            // dependence graph
  66   _visited(arena()),                      // visited node set
  67   _post_visited(arena()),                 // post visited node set
  68   _n_idx_list(arena(), 8),                // scratch list of (node,index) pairs
  69   _nlist(arena(), 8, 0, NULL),            // scratch list of nodes
  70   _stk(arena(), 8, 0, NULL),              // scratch stack of nodes
  71   _lpt(NULL),                             // loop tree node
  72   _lp(NULL),                              // LoopNode
  73   _bb(NULL),                              // basic block
  74   _iv(NULL),                              // induction var
  75   _race_possible(false),                  // cases where SDMU is true
  76   _early_return(true),                    // analysis evaluations routine
  77   _do_vector_loop(phase->C->do_vector_loop()),  // whether to do vectorization/simd style
  78   _do_reserve_copy(DoReserveCopyInSuperWord),
  79   _num_work_vecs(0),                      // amount of vector work we have
  80   _num_reductions(0),                     // amount of reduction work we have
  81   _ii_first(-1),                          // first loop generation index - only if do_vector_loop()
  82   _ii_last(-1),                           // last loop generation index - only if do_vector_loop()
  83   _ii_order(arena(), 8, 0, 0)
  84 {
  85 #ifndef PRODUCT
  86   _vector_loop_debug = 0;
  87   if (_phase->C->method() != NULL) {
  88     _vector_loop_debug = phase->C->directive()->VectorizeDebugOption;
  89   }
  90 
  91 #endif
  92 }
  93 
  94 //------------------------------transform_loop---------------------------
  95 void SuperWord::transform_loop(IdealLoopTree* lpt, bool do_optimization) {
  96   assert(UseSuperWord, "should be");
  97   // SuperWord only works with power of two vector sizes.
  98   int vector_width = Matcher::vector_width_in_bytes(T_BYTE);
  99   if (vector_width < 2 || !is_power_of_2(vector_width)) {
 100     return;
 101   }
 102 
 103   assert(lpt->_head->is_CountedLoop(), "must be");
 104   CountedLoopNode *cl = lpt->_head->as_CountedLoop();
 105 
 106   if (!cl->is_valid_counted_loop()) return; // skip malformed counted loop
 107 
 108   bool post_loop_allowed = (PostLoopMultiversioning && Matcher::has_predicated_vectors() && cl->is_post_loop());
 109   if (post_loop_allowed) {
 110     if (cl->is_reduction_loop()) return; // no predication mapping
 111     Node *limit = cl->limit();
 112     if (limit->is_Con()) return; // non constant limits only
 113     // Now check the limit for expressions we do not handle
 114     if (limit->is_Add()) {
 115       Node *in2 = limit->in(2);
 116       if (in2->is_Con()) {
 117         int val = in2->get_int();
 118         // should not try to program these cases
 119         if (val < 0) return;
 120       }
 121     }
 122   }
 123 
 124   // skip any loop that has not been assigned max unroll by analysis
 125   if (do_optimization) {
 126     if (SuperWordLoopUnrollAnalysis && cl->slp_max_unroll() == 0) return;
 127   }
 128 
 129   // Check for no control flow in body (other than exit)
 130   Node *cl_exit = cl->loopexit();
 131   if (cl->is_main_loop() && (cl_exit->in(0) != lpt->_head)) {
 132     #ifndef PRODUCT
 133       if (TraceSuperWord) {
 134         tty->print_cr("SuperWord::transform_loop: loop too complicated, cl_exit->in(0) != lpt->_head");
 135         tty->print("cl_exit %d", cl_exit->_idx); cl_exit->dump();
 136         tty->print("cl_exit->in(0) %d", cl_exit->in(0)->_idx); cl_exit->in(0)->dump();
 137         tty->print("lpt->_head %d", lpt->_head->_idx); lpt->_head->dump();
 138         lpt->dump_head();
 139       }
 140     #endif
 141     return;
 142   }
 143 
 144   // Make sure the are no extra control users of the loop backedge
 145   if (cl->back_control()->outcnt() != 1) {
 146     return;
 147   }
 148 
 149   // Skip any loops already optimized by slp
 150   if (cl->is_vectorized_loop()) return;
 151 
 152   if (cl->is_unroll_only()) return;
 153 
 154   if (cl->is_main_loop()) {
 155     // Check for pre-loop ending with CountedLoopEnd(Bool(Cmp(x,Opaque1(limit))))
 156     CountedLoopEndNode* pre_end = get_pre_loop_end(cl);
 157     if (pre_end == NULL) return;
 158     Node *pre_opaq1 = pre_end->limit();
 159     if (pre_opaq1->Opcode() != Op_Opaque1) return;
 160   }
 161 
 162   init(); // initialize data structures
 163 
 164   set_lpt(lpt);
 165   set_lp(cl);
 166 
 167   // For now, define one block which is the entire loop body
 168   set_bb(cl);
 169 
 170   if (do_optimization) {
 171     assert(_packset.length() == 0, "packset must be empty");
 172     SLP_extract();
 173     if (PostLoopMultiversioning && Matcher::has_predicated_vectors()) {
 174       if (cl->is_vectorized_loop() && cl->is_main_loop() && !cl->is_reduction_loop()) {
 175         IdealLoopTree *lpt_next = lpt->_next;
 176         CountedLoopNode *cl_next = lpt_next->_head->as_CountedLoop();
 177         _phase->has_range_checks(lpt_next);
 178         if (cl_next->is_post_loop() && !cl_next->range_checks_present()) {
 179           if (!cl_next->is_vectorized_loop()) {
 180             int slp_max_unroll_factor = cl->slp_max_unroll();
 181             cl_next->set_slp_max_unroll(slp_max_unroll_factor);
 182           }
 183         }
 184       }
 185     }
 186   }
 187 }
 188 
 189 //------------------------------early unrolling analysis------------------------------
 190 void SuperWord::unrolling_analysis(int &local_loop_unroll_factor) {
 191   bool is_slp = true;
 192   ResourceMark rm;
 193   size_t ignored_size = lpt()->_body.size();
 194   int *ignored_loop_nodes = NEW_RESOURCE_ARRAY(int, ignored_size);
 195   Node_Stack nstack((int)ignored_size);
 196   CountedLoopNode *cl = lpt()->_head->as_CountedLoop();
 197   Node *cl_exit = cl->loopexit_or_null();
 198   int rpo_idx = _post_block.length();
 199 
 200   assert(rpo_idx == 0, "post loop block is empty");
 201 
 202   // First clear the entries
 203   for (uint i = 0; i < lpt()->_body.size(); i++) {
 204     ignored_loop_nodes[i] = -1;
 205   }
 206 
 207   int max_vector = Matcher::max_vector_size(T_BYTE);
 208   bool post_loop_allowed = (PostLoopMultiversioning && Matcher::has_predicated_vectors() && cl->is_post_loop());
 209 
 210   // Process the loop, some/all of the stack entries will not be in order, ergo
 211   // need to preprocess the ignored initial state before we process the loop
 212   for (uint i = 0; i < lpt()->_body.size(); i++) {
 213     Node* n = lpt()->_body.at(i);
 214     if (n == cl->incr() ||
 215       n->is_reduction() ||
 216       n->is_AddP() ||
 217       n->is_Cmp() ||
 218       n->is_IfTrue() ||
 219       n->is_CountedLoop() ||
 220       (n == cl_exit)) {
 221       ignored_loop_nodes[i] = n->_idx;
 222       continue;
 223     }
 224 
 225     if (n->is_If()) {
 226       IfNode *iff = n->as_If();
 227       if (iff->_fcnt != COUNT_UNKNOWN && iff->_prob != PROB_UNKNOWN) {
 228         if (lpt()->is_loop_exit(iff)) {
 229           ignored_loop_nodes[i] = n->_idx;
 230           continue;
 231         }
 232       }
 233     }
 234 
 235     if (n->is_Phi() && (n->bottom_type() == Type::MEMORY)) {
 236       Node* n_tail = n->in(LoopNode::LoopBackControl);
 237       if (n_tail != n->in(LoopNode::EntryControl)) {
 238         if (!n_tail->is_Mem()) {
 239           is_slp = false;
 240           break;
 241         }
 242       }
 243     }
 244 
 245     // This must happen after check of phi/if
 246     if (n->is_Phi() || n->is_If()) {
 247       ignored_loop_nodes[i] = n->_idx;
 248       continue;
 249     }
 250 
 251     if (n->is_LoadStore() || n->is_MergeMem() ||
 252       (n->is_Proj() && !n->as_Proj()->is_CFG())) {
 253       is_slp = false;
 254       break;
 255     }
 256 
 257     // Ignore nodes with non-primitive type.
 258     BasicType bt;
 259     if (n->is_Mem()) {
 260       bt = n->as_Mem()->memory_type();
 261     } else {
 262       bt = n->bottom_type()->basic_type();
 263     }
 264     if (is_java_primitive(bt) == false) {
 265       ignored_loop_nodes[i] = n->_idx;
 266       continue;
 267     }
 268 
 269     if (n->is_Mem()) {
 270       MemNode* current = n->as_Mem();
 271       Node* adr = n->in(MemNode::Address);
 272       Node* n_ctrl = _phase->get_ctrl(adr);
 273 
 274       // save a queue of post process nodes
 275       if (n_ctrl != NULL && lpt()->is_member(_phase->get_loop(n_ctrl))) {
 276         // Process the memory expression
 277         int stack_idx = 0;
 278         bool have_side_effects = true;
 279         if (adr->is_AddP() == false) {
 280           nstack.push(adr, stack_idx++);
 281         } else {
 282           // Mark the components of the memory operation in nstack
 283           SWPointer p1(current, this, &nstack, true);
 284           have_side_effects = p1.node_stack()->is_nonempty();
 285         }
 286 
 287         // Process the pointer stack
 288         while (have_side_effects) {
 289           Node* pointer_node = nstack.node();
 290           for (uint j = 0; j < lpt()->_body.size(); j++) {
 291             Node* cur_node = lpt()->_body.at(j);
 292             if (cur_node == pointer_node) {
 293               ignored_loop_nodes[j] = cur_node->_idx;
 294               break;
 295             }
 296           }
 297           nstack.pop();
 298           have_side_effects = nstack.is_nonempty();
 299         }
 300       }
 301     }
 302   }
 303 
 304   if (is_slp) {
 305     // Now we try to find the maximum supported consistent vector which the machine
 306     // description can use
 307     bool small_basic_type = false;
 308     bool flag_small_bt = false;
 309     for (uint i = 0; i < lpt()->_body.size(); i++) {
 310       if (ignored_loop_nodes[i] != -1) continue;
 311 
 312       BasicType bt;
 313       Node* n = lpt()->_body.at(i);
 314       if (n->is_Mem()) {
 315         bt = n->as_Mem()->memory_type();
 316       } else {
 317         bt = n->bottom_type()->basic_type();
 318       }
 319 
 320       if (post_loop_allowed) {
 321         if (!small_basic_type) {
 322           switch (bt) {
 323           case T_CHAR:
 324           case T_BYTE:
 325           case T_SHORT:
 326             small_basic_type = true;
 327             break;
 328 
 329           case T_LONG:
 330             // TODO: Remove when support completed for mask context with LONG.
 331             //       Support needs to be augmented for logical qword operations, currently we map to dword
 332             //       buckets for vectors on logicals as these were legacy.
 333             small_basic_type = true;
 334             break;
 335 
 336           default:
 337             break;
 338           }
 339         }
 340       }
 341 
 342       if (is_java_primitive(bt) == false) continue;
 343 
 344          int cur_max_vector = Matcher::max_vector_size(bt);
 345 
 346       // If a max vector exists which is not larger than _local_loop_unroll_factor
 347       // stop looking, we already have the max vector to map to.
 348       if (cur_max_vector < local_loop_unroll_factor) {
 349         is_slp = false;
 350         if (TraceSuperWordLoopUnrollAnalysis) {
 351           tty->print_cr("slp analysis fails: unroll limit greater than max vector\n");
 352         }
 353         break;
 354       }
 355 
 356       // Map the maximal common vector
 357       if (VectorNode::implemented(n->Opcode(), cur_max_vector, bt)) {
 358         if (cur_max_vector < max_vector && !flag_small_bt) {
 359           max_vector = cur_max_vector;
 360         } else if (cur_max_vector > max_vector && UseSubwordForMaxVector) {
 361           // Analyse subword in the loop to set maximum vector size to take advantage of full vector width for subword types.
 362           // Here we analyze if narrowing is likely to happen and if it is we set vector size more aggressively.
 363           // We check for possibility of narrowing by looking through chain operations using subword types.
 364           if (is_subword_type(bt)) {
 365             uint start, end;
 366             VectorNode::vector_operands(n, &start, &end);
 367 
 368             for (uint j = start; j < end; j++) {
 369               Node* in = n->in(j);
 370               // Don't propagate through a memory
 371               if (!in->is_Mem() && in_bb(in) && in->bottom_type()->basic_type() == T_INT) {
 372                 bool same_type = true;
 373                 for (DUIterator_Fast kmax, k = in->fast_outs(kmax); k < kmax; k++) {
 374                   Node *use = in->fast_out(k);
 375                   if (!in_bb(use) && use->bottom_type()->basic_type() != bt) {
 376                     same_type = false;
 377                     break;
 378                   }
 379                 }
 380                 if (same_type) {
 381                   max_vector = cur_max_vector;
 382                   flag_small_bt = true;
 383                   cl->mark_subword_loop();
 384                 }
 385               }
 386             }
 387           }
 388         }
 389         // We only process post loops on predicated targets where we want to
 390         // mask map the loop to a single iteration
 391         if (post_loop_allowed) {
 392           _post_block.at_put_grow(rpo_idx++, n);
 393         }
 394       }
 395     }
 396     if (is_slp) {
 397       local_loop_unroll_factor = max_vector;
 398       cl->mark_passed_slp();
 399     }
 400     cl->mark_was_slp();
 401     if (cl->is_main_loop()) {
 402       cl->set_slp_max_unroll(local_loop_unroll_factor);
 403     } else if (post_loop_allowed) {
 404       if (!small_basic_type) {
 405         // avoid replication context for small basic types in programmable masked loops
 406         cl->set_slp_max_unroll(local_loop_unroll_factor);
 407       }
 408     }
 409   }
 410 }
 411 
 412 //------------------------------SLP_extract---------------------------
 413 // Extract the superword level parallelism
 414 //
 415 // 1) A reverse post-order of nodes in the block is constructed.  By scanning
 416 //    this list from first to last, all definitions are visited before their uses.
 417 //
 418 // 2) A point-to-point dependence graph is constructed between memory references.
 419 //    This simplies the upcoming "independence" checker.
 420 //
 421 // 3) The maximum depth in the node graph from the beginning of the block
 422 //    to each node is computed.  This is used to prune the graph search
 423 //    in the independence checker.
 424 //
 425 // 4) For integer types, the necessary bit width is propagated backwards
 426 //    from stores to allow packed operations on byte, char, and short
 427 //    integers.  This reverses the promotion to type "int" that javac
 428 //    did for operations like: char c1,c2,c3;  c1 = c2 + c3.
 429 //
 430 // 5) One of the memory references is picked to be an aligned vector reference.
 431 //    The pre-loop trip count is adjusted to align this reference in the
 432 //    unrolled body.
 433 //
 434 // 6) The initial set of pack pairs is seeded with memory references.
 435 //
 436 // 7) The set of pack pairs is extended by following use->def and def->use links.
 437 //
 438 // 8) The pairs are combined into vector sized packs.
 439 //
 440 // 9) Reorder the memory slices to co-locate members of the memory packs.
 441 //
 442 // 10) Generate ideal vector nodes for the final set of packs and where necessary,
 443 //    inserting scalar promotion, vector creation from multiple scalars, and
 444 //    extraction of scalar values from vectors.
 445 //
 446 void SuperWord::SLP_extract() {
 447 
 448 #ifndef PRODUCT
 449   if (_do_vector_loop && TraceSuperWord) {
 450     tty->print("SuperWord::SLP_extract\n");
 451     tty->print("input loop\n");
 452     _lpt->dump_head();
 453     _lpt->dump();
 454     for (uint i = 0; i < _lpt->_body.size(); i++) {
 455       _lpt->_body.at(i)->dump();
 456     }
 457   }
 458 #endif
 459   // Ready the block
 460   if (!construct_bb()) {
 461     return; // Exit if no interesting nodes or complex graph.
 462   }
 463 
 464   // build    _dg, _disjoint_ptrs
 465   dependence_graph();
 466 
 467   // compute function depth(Node*)
 468   compute_max_depth();
 469 
 470   CountedLoopNode *cl = lpt()->_head->as_CountedLoop();
 471   bool post_loop_allowed = (PostLoopMultiversioning && Matcher::has_predicated_vectors() && cl->is_post_loop());
 472   if (cl->is_main_loop()) {
 473     if (_do_vector_loop) {
 474       if (mark_generations() != -1) {
 475         hoist_loads_in_graph(); // this only rebuild the graph; all basic structs need rebuild explicitly
 476 
 477         if (!construct_bb()) {
 478           return; // Exit if no interesting nodes or complex graph.
 479         }
 480         dependence_graph();
 481         compute_max_depth();
 482       }
 483 
 484 #ifndef PRODUCT
 485       if (TraceSuperWord) {
 486         tty->print_cr("\nSuperWord::_do_vector_loop: graph after hoist_loads_in_graph");
 487         _lpt->dump_head();
 488         for (int j = 0; j < _block.length(); j++) {
 489           Node* n = _block.at(j);
 490           int d = depth(n);
 491           for (int i = 0; i < d; i++) tty->print("%s", "  ");
 492           tty->print("%d :", d);
 493           n->dump();
 494         }
 495       }
 496 #endif
 497     }
 498 
 499     compute_vector_element_type();
 500 
 501     // Attempt vectorization
 502 
 503     find_adjacent_refs();
 504 
 505     if (align_to_ref() == NULL) {
 506       return; // Did not find memory reference to align vectors
 507     }
 508 
 509     extend_packlist();
 510 
 511     if (_do_vector_loop) {
 512       if (_packset.length() == 0) {
 513         if (TraceSuperWord) {
 514           tty->print_cr("\nSuperWord::_do_vector_loop DFA could not build packset, now trying to build anyway");
 515         }
 516         pack_parallel();
 517       }
 518     }
 519 
 520     combine_packs();
 521 
 522     construct_my_pack_map();
 523     if (UseVectorCmov) {
 524       merge_packs_to_cmovd();
 525     }
 526 
 527     filter_packs();
 528 
 529     schedule();
 530   } else if (post_loop_allowed) {
 531     int saved_mapped_unroll_factor = cl->slp_max_unroll();
 532     if (saved_mapped_unroll_factor) {
 533       int vector_mapped_unroll_factor = saved_mapped_unroll_factor;
 534 
 535       // now reset the slp_unroll_factor so that we can check the analysis mapped
 536       // what the vector loop was mapped to
 537       cl->set_slp_max_unroll(0);
 538 
 539       // do the analysis on the post loop
 540       unrolling_analysis(vector_mapped_unroll_factor);
 541 
 542       // if our analyzed loop is a canonical fit, start processing it
 543       if (vector_mapped_unroll_factor == saved_mapped_unroll_factor) {
 544         // now add the vector nodes to packsets
 545         for (int i = 0; i < _post_block.length(); i++) {
 546           Node* n = _post_block.at(i);
 547           Node_List* singleton = new Node_List();
 548           singleton->push(n);
 549           _packset.append(singleton);
 550           set_my_pack(n, singleton);
 551         }
 552 
 553         // map base types for vector usage
 554         compute_vector_element_type();
 555       } else {
 556         return;
 557       }
 558     } else {
 559       // for some reason we could not map the slp analysis state of the vectorized loop
 560       return;
 561     }
 562   }
 563 
 564   output();
 565 }
 566 
 567 //------------------------------find_adjacent_refs---------------------------
 568 // Find the adjacent memory references and create pack pairs for them.
 569 // This is the initial set of packs that will then be extended by
 570 // following use->def and def->use links.  The align positions are
 571 // assigned relative to the reference "align_to_ref"
 572 void SuperWord::find_adjacent_refs() {
 573   // Get list of memory operations
 574   Node_List memops;
 575   for (int i = 0; i < _block.length(); i++) {
 576     Node* n = _block.at(i);
 577     if (n->is_Mem() && !n->is_LoadStore() && in_bb(n) &&
 578         is_java_primitive(n->as_Mem()->memory_type())) {
 579       int align = memory_alignment(n->as_Mem(), 0);
 580       if (align != bottom_align) {
 581         memops.push(n);
 582       }
 583     }
 584   }
 585   if (TraceSuperWord) {
 586     tty->print_cr("\nfind_adjacent_refs found %d memops", memops.size());
 587   }
 588 
 589   Node_List align_to_refs;
 590   int max_idx;
 591   int best_iv_adjustment = 0;
 592   MemNode* best_align_to_mem_ref = NULL;
 593 
 594   while (memops.size() != 0) {
 595     // Find a memory reference to align to.
 596     MemNode* mem_ref = find_align_to_ref(memops, max_idx);
 597     if (mem_ref == NULL) break;
 598     align_to_refs.push(mem_ref);
 599     int iv_adjustment = get_iv_adjustment(mem_ref);
 600 
 601     if (best_align_to_mem_ref == NULL) {
 602       // Set memory reference which is the best from all memory operations
 603       // to be used for alignment. The pre-loop trip count is modified to align
 604       // this reference to a vector-aligned address.
 605       best_align_to_mem_ref = mem_ref;
 606       best_iv_adjustment = iv_adjustment;
 607       NOT_PRODUCT(find_adjacent_refs_trace_1(best_align_to_mem_ref, best_iv_adjustment);)
 608     }
 609 
 610     SWPointer align_to_ref_p(mem_ref, this, NULL, false);
 611     // Set alignment relative to "align_to_ref" for all related memory operations.
 612     for (int i = memops.size() - 1; i >= 0; i--) {
 613       MemNode* s = memops.at(i)->as_Mem();
 614       if (isomorphic(s, mem_ref) &&
 615            (!_do_vector_loop || same_origin_idx(s, mem_ref))) {
 616         SWPointer p2(s, this, NULL, false);
 617         if (p2.comparable(align_to_ref_p)) {
 618           int align = memory_alignment(s, iv_adjustment);
 619           set_alignment(s, align);
 620         }
 621       }
 622     }
 623 
 624     // Create initial pack pairs of memory operations for which
 625     // alignment is set and vectors will be aligned.
 626     bool create_pack = true;
 627     if (memory_alignment(mem_ref, best_iv_adjustment) == 0 || _do_vector_loop) {
 628       if (vectors_should_be_aligned()) {
 629         int vw = vector_width(mem_ref);
 630         int vw_best = vector_width(best_align_to_mem_ref);
 631         if (vw > vw_best) {
 632           // Do not vectorize a memory access with more elements per vector
 633           // if unaligned memory access is not allowed because number of
 634           // iterations in pre-loop will be not enough to align it.
 635           create_pack = false;
 636         } else {
 637           SWPointer p2(best_align_to_mem_ref, this, NULL, false);
 638           if (align_to_ref_p.invar() != p2.invar()) {
 639             // Do not vectorize memory accesses with different invariants
 640             // if unaligned memory accesses are not allowed.
 641             create_pack = false;
 642           }
 643         }
 644       }
 645     } else {
 646       if (same_velt_type(mem_ref, best_align_to_mem_ref)) {
 647         // Can't allow vectorization of unaligned memory accesses with the
 648         // same type since it could be overlapped accesses to the same array.
 649         create_pack = false;
 650       } else {
 651         // Allow independent (different type) unaligned memory operations
 652         // if HW supports them.
 653         if (vectors_should_be_aligned()) {
 654           create_pack = false;
 655         } else {
 656           // Check if packs of the same memory type but
 657           // with a different alignment were created before.
 658           for (uint i = 0; i < align_to_refs.size(); i++) {
 659             MemNode* mr = align_to_refs.at(i)->as_Mem();
 660             if (mr == mem_ref) {
 661               // Skip when we are looking at same memory operation.
 662               continue;
 663             }
 664             if (same_velt_type(mr, mem_ref) &&
 665                 memory_alignment(mr, iv_adjustment) != 0)
 666               create_pack = false;
 667           }
 668         }
 669       }
 670     }
 671     if (create_pack) {
 672       for (uint i = 0; i < memops.size(); i++) {
 673         Node* s1 = memops.at(i);
 674         int align = alignment(s1);
 675         if (align == top_align) continue;
 676         for (uint j = 0; j < memops.size(); j++) {
 677           Node* s2 = memops.at(j);
 678           if (alignment(s2) == top_align) continue;
 679           if (s1 != s2 && are_adjacent_refs(s1, s2)) {
 680             if (stmts_can_pack(s1, s2, align)) {
 681               Node_List* pair = new Node_List();
 682               pair->push(s1);
 683               pair->push(s2);
 684               if (!_do_vector_loop || same_origin_idx(s1, s2)) {
 685                 _packset.append(pair);
 686               }
 687             }
 688           }
 689         }
 690       }
 691     } else { // Don't create unaligned pack
 692       // First, remove remaining memory ops of the same type from the list.
 693       for (int i = memops.size() - 1; i >= 0; i--) {
 694         MemNode* s = memops.at(i)->as_Mem();
 695         if (same_velt_type(s, mem_ref)) {
 696           memops.remove(i);
 697         }
 698       }
 699 
 700       // Second, remove already constructed packs of the same type.
 701       for (int i = _packset.length() - 1; i >= 0; i--) {
 702         Node_List* p = _packset.at(i);
 703         MemNode* s = p->at(0)->as_Mem();
 704         if (same_velt_type(s, mem_ref)) {
 705           remove_pack_at(i);
 706         }
 707       }
 708 
 709       // If needed find the best memory reference for loop alignment again.
 710       if (same_velt_type(mem_ref, best_align_to_mem_ref)) {
 711         // Put memory ops from remaining packs back on memops list for
 712         // the best alignment search.
 713         uint orig_msize = memops.size();
 714         for (int i = 0; i < _packset.length(); i++) {
 715           Node_List* p = _packset.at(i);
 716           MemNode* s = p->at(0)->as_Mem();
 717           assert(!same_velt_type(s, mem_ref), "sanity");
 718           memops.push(s);
 719         }
 720         best_align_to_mem_ref = find_align_to_ref(memops, max_idx);
 721         if (best_align_to_mem_ref == NULL) {
 722           if (TraceSuperWord) {
 723             tty->print_cr("SuperWord::find_adjacent_refs(): best_align_to_mem_ref == NULL");
 724           }
 725           // best_align_to_mem_ref will be used for adjusting the pre-loop limit in
 726           // SuperWord::align_initial_loop_index. Find one with the biggest vector size,
 727           // smallest data size and smallest iv offset from memory ops from remaining packs.
 728           if (_packset.length() > 0) {
 729             if (orig_msize == 0) {
 730               best_align_to_mem_ref = memops.at(max_idx)->as_Mem();
 731             } else {
 732               for (uint i = 0; i < orig_msize; i++) {
 733                 memops.remove(0);
 734               }
 735               best_align_to_mem_ref = find_align_to_ref(memops, max_idx);
 736               assert(best_align_to_mem_ref == NULL, "sanity");
 737               best_align_to_mem_ref = memops.at(max_idx)->as_Mem();
 738             }
 739             assert(best_align_to_mem_ref != NULL, "sanity");
 740           }
 741           break;
 742         }
 743         best_iv_adjustment = get_iv_adjustment(best_align_to_mem_ref);
 744         NOT_PRODUCT(find_adjacent_refs_trace_1(best_align_to_mem_ref, best_iv_adjustment);)
 745         // Restore list.
 746         while (memops.size() > orig_msize)
 747           (void)memops.pop();
 748       }
 749     } // unaligned memory accesses
 750 
 751     // Remove used mem nodes.
 752     for (int i = memops.size() - 1; i >= 0; i--) {
 753       MemNode* m = memops.at(i)->as_Mem();
 754       if (alignment(m) != top_align) {
 755         memops.remove(i);
 756       }
 757     }
 758 
 759   } // while (memops.size() != 0
 760   set_align_to_ref(best_align_to_mem_ref);
 761 
 762   if (TraceSuperWord) {
 763     tty->print_cr("\nAfter find_adjacent_refs");
 764     print_packset();
 765   }
 766 }
 767 
 768 #ifndef PRODUCT
 769 void SuperWord::find_adjacent_refs_trace_1(Node* best_align_to_mem_ref, int best_iv_adjustment) {
 770   if (is_trace_adjacent()) {
 771     tty->print("SuperWord::find_adjacent_refs best_align_to_mem_ref = %d, best_iv_adjustment = %d",
 772        best_align_to_mem_ref->_idx, best_iv_adjustment);
 773        best_align_to_mem_ref->dump();
 774   }
 775 }
 776 #endif
 777 
 778 //------------------------------find_align_to_ref---------------------------
 779 // Find a memory reference to align the loop induction variable to.
 780 // Looks first at stores then at loads, looking for a memory reference
 781 // with the largest number of references similar to it.
 782 MemNode* SuperWord::find_align_to_ref(Node_List &memops, int &idx) {
 783   GrowableArray<int> cmp_ct(arena(), memops.size(), memops.size(), 0);
 784 
 785   // Count number of comparable memory ops
 786   for (uint i = 0; i < memops.size(); i++) {
 787     MemNode* s1 = memops.at(i)->as_Mem();
 788     SWPointer p1(s1, this, NULL, false);
 789     // Only discard unalignable memory references if vector memory references
 790     // should be aligned on this platform.
 791     if (vectors_should_be_aligned() && !ref_is_alignable(p1)) {
 792       *cmp_ct.adr_at(i) = 0;
 793       continue;
 794     }
 795     for (uint j = i+1; j < memops.size(); j++) {
 796       MemNode* s2 = memops.at(j)->as_Mem();
 797       if (isomorphic(s1, s2)) {
 798         SWPointer p2(s2, this, NULL, false);
 799         if (p1.comparable(p2)) {
 800           (*cmp_ct.adr_at(i))++;
 801           (*cmp_ct.adr_at(j))++;
 802         }
 803       }
 804     }
 805   }
 806 
 807   // Find Store (or Load) with the greatest number of "comparable" references,
 808   // biggest vector size, smallest data size and smallest iv offset.
 809   int max_ct        = 0;
 810   int max_vw        = 0;
 811   int max_idx       = -1;
 812   int min_size      = max_jint;
 813   int min_iv_offset = max_jint;
 814   for (uint j = 0; j < memops.size(); j++) {
 815     MemNode* s = memops.at(j)->as_Mem();
 816     if (s->is_Store()) {
 817       int vw = vector_width_in_bytes(s);
 818       assert(vw > 1, "sanity");
 819       SWPointer p(s, this, NULL, false);
 820       if ( cmp_ct.at(j) >  max_ct ||
 821           (cmp_ct.at(j) == max_ct &&
 822             ( vw >  max_vw ||
 823              (vw == max_vw &&
 824               ( data_size(s) <  min_size ||
 825                (data_size(s) == min_size &&
 826                 p.offset_in_bytes() < min_iv_offset)))))) {
 827         max_ct = cmp_ct.at(j);
 828         max_vw = vw;
 829         max_idx = j;
 830         min_size = data_size(s);
 831         min_iv_offset = p.offset_in_bytes();
 832       }
 833     }
 834   }
 835   // If no stores, look at loads
 836   if (max_ct == 0) {
 837     for (uint j = 0; j < memops.size(); j++) {
 838       MemNode* s = memops.at(j)->as_Mem();
 839       if (s->is_Load()) {
 840         int vw = vector_width_in_bytes(s);
 841         assert(vw > 1, "sanity");
 842         SWPointer p(s, this, NULL, false);
 843         if ( cmp_ct.at(j) >  max_ct ||
 844             (cmp_ct.at(j) == max_ct &&
 845               ( vw >  max_vw ||
 846                (vw == max_vw &&
 847                 ( data_size(s) <  min_size ||
 848                  (data_size(s) == min_size &&
 849                   p.offset_in_bytes() < min_iv_offset)))))) {
 850           max_ct = cmp_ct.at(j);
 851           max_vw = vw;
 852           max_idx = j;
 853           min_size = data_size(s);
 854           min_iv_offset = p.offset_in_bytes();
 855         }
 856       }
 857     }
 858   }
 859 
 860 #ifdef ASSERT
 861   if (TraceSuperWord && Verbose) {
 862     tty->print_cr("\nVector memops after find_align_to_ref");
 863     for (uint i = 0; i < memops.size(); i++) {
 864       MemNode* s = memops.at(i)->as_Mem();
 865       s->dump();
 866     }
 867   }
 868 #endif
 869 
 870   idx = max_idx;
 871   if (max_ct > 0) {
 872 #ifdef ASSERT
 873     if (TraceSuperWord) {
 874       tty->print("\nVector align to node: ");
 875       memops.at(max_idx)->as_Mem()->dump();
 876     }
 877 #endif
 878     return memops.at(max_idx)->as_Mem();
 879   }
 880   return NULL;
 881 }
 882 
 883 //------------------span_works_for_memory_size-----------------------------
 884 static bool span_works_for_memory_size(MemNode* mem, int span, int mem_size, int offset) {
 885   bool span_matches_memory = false;
 886   if ((mem_size == type2aelembytes(T_BYTE) || mem_size == type2aelembytes(T_SHORT))
 887     && ABS(span) == type2aelembytes(T_INT)) {
 888     // There is a mismatch on span size compared to memory.
 889     for (DUIterator_Fast jmax, j = mem->fast_outs(jmax); j < jmax; j++) {
 890       Node* use = mem->fast_out(j);
 891       if (!VectorNode::is_type_transition_to_int(use)) {
 892         return false;
 893       }
 894     }
 895     // If all uses transition to integer, it means that we can successfully align even on mismatch.
 896     return true;
 897   }
 898   else {
 899     span_matches_memory = ABS(span) == mem_size;
 900   }
 901   return span_matches_memory && (ABS(offset) % mem_size) == 0;
 902 }
 903 
 904 //------------------------------ref_is_alignable---------------------------
 905 // Can the preloop align the reference to position zero in the vector?
 906 bool SuperWord::ref_is_alignable(SWPointer& p) {
 907   if (!p.has_iv()) {
 908     return true;   // no induction variable
 909   }
 910   CountedLoopEndNode* pre_end = get_pre_loop_end(lp()->as_CountedLoop());
 911   assert(pre_end != NULL, "we must have a correct pre-loop");
 912   assert(pre_end->stride_is_con(), "pre loop stride is constant");
 913   int preloop_stride = pre_end->stride_con();
 914 
 915   int span = preloop_stride * p.scale_in_bytes();
 916   int mem_size = p.memory_size();
 917   int offset   = p.offset_in_bytes();
 918   // Stride one accesses are alignable if offset is aligned to memory operation size.
 919   // Offset can be unaligned when UseUnalignedAccesses is used.
 920   if (span_works_for_memory_size(p.mem(), span, mem_size, offset)) {
 921     return true;
 922   }
 923   // If the initial offset from start of the object is computable,
 924   // check if the pre-loop can align the final offset accordingly.
 925   //
 926   // In other words: Can we find an i such that the offset
 927   // after i pre-loop iterations is aligned to vw?
 928   //   (init_offset + pre_loop) % vw == 0              (1)
 929   // where
 930   //   pre_loop = i * span
 931   // is the number of bytes added to the offset by i pre-loop iterations.
 932   //
 933   // For this to hold we need pre_loop to increase init_offset by
 934   //   pre_loop = vw - (init_offset % vw)
 935   //
 936   // This is only possible if pre_loop is divisible by span because each
 937   // pre-loop iteration increases the initial offset by 'span' bytes:
 938   //   (vw - (init_offset % vw)) % span == 0
 939   //
 940   int vw = vector_width_in_bytes(p.mem());
 941   assert(vw > 1, "sanity");
 942   Node* init_nd = pre_end->init_trip();
 943   if (init_nd->is_Con() && p.invar() == NULL) {
 944     int init = init_nd->bottom_type()->is_int()->get_con();
 945     int init_offset = init * p.scale_in_bytes() + offset;
 946     if (init_offset < 0) { // negative offset from object start?
 947       return false;        // may happen in dead loop
 948     }
 949     if (vw % span == 0) {
 950       // If vm is a multiple of span, we use formula (1).
 951       if (span > 0) {
 952         return (vw - (init_offset % vw)) % span == 0;
 953       } else {
 954         assert(span < 0, "nonzero stride * scale");
 955         return (init_offset % vw) % -span == 0;
 956       }
 957     } else if (span % vw == 0) {
 958       // If span is a multiple of vw, we can simplify formula (1) to:
 959       //   (init_offset + i * span) % vw == 0
 960       //     =>
 961       //   (init_offset % vw) + ((i * span) % vw) == 0
 962       //     =>
 963       //   init_offset % vw == 0
 964       //
 965       // Because we add a multiple of vw to the initial offset, the final
 966       // offset is a multiple of vw if and only if init_offset is a multiple.
 967       //
 968       return (init_offset % vw) == 0;
 969     }
 970   }
 971   return false;
 972 }
 973 //---------------------------get_vw_bytes_special------------------------
 974 int SuperWord::get_vw_bytes_special(MemNode* s) {
 975   // Get the vector width in bytes.
 976   int vw = vector_width_in_bytes(s);
 977 
 978   // Check for special case where there is an MulAddS2I usage where short vectors are going to need combined.
 979   BasicType btype = velt_basic_type(s);
 980   if (type2aelembytes(btype) == 2) {
 981     bool should_combine_adjacent = true;
 982     for (DUIterator_Fast imax, i = s->fast_outs(imax); i < imax; i++) {
 983       Node* user = s->fast_out(i);
 984       if (!VectorNode::is_muladds2i(user)) {
 985         should_combine_adjacent = false;
 986       }
 987     }
 988     if (should_combine_adjacent) {
 989       vw = MIN2(Matcher::max_vector_size(btype)*type2aelembytes(btype), vw * 2);
 990     }
 991   }
 992 
 993   return vw;
 994 }
 995 
 996 //---------------------------get_iv_adjustment---------------------------
 997 // Calculate loop's iv adjustment for this memory ops.
 998 int SuperWord::get_iv_adjustment(MemNode* mem_ref) {
 999   SWPointer align_to_ref_p(mem_ref, this, NULL, false);
1000   int offset = align_to_ref_p.offset_in_bytes();
1001   int scale  = align_to_ref_p.scale_in_bytes();
1002   int elt_size = align_to_ref_p.memory_size();
1003   int vw       = get_vw_bytes_special(mem_ref);
1004   assert(vw > 1, "sanity");
1005   int iv_adjustment;
1006   if (scale != 0) {
1007     int stride_sign = (scale * iv_stride()) > 0 ? 1 : -1;
1008     // At least one iteration is executed in pre-loop by default. As result
1009     // several iterations are needed to align memory operations in main-loop even
1010     // if offset is 0.
1011     int iv_adjustment_in_bytes = (stride_sign * vw - (offset % vw));
1012     // iv_adjustment_in_bytes must be a multiple of elt_size if vector memory
1013     // references should be aligned on this platform.
1014     assert((ABS(iv_adjustment_in_bytes) % elt_size) == 0 || !vectors_should_be_aligned(),
1015            "(%d) should be divisible by (%d)", iv_adjustment_in_bytes, elt_size);
1016     iv_adjustment = iv_adjustment_in_bytes/elt_size;
1017   } else {
1018     // This memory op is not dependent on iv (scale == 0)
1019     iv_adjustment = 0;
1020   }
1021 
1022 #ifndef PRODUCT
1023   if (TraceSuperWord) {
1024     tty->print("SuperWord::get_iv_adjustment: n = %d, noffset = %d iv_adjust = %d elt_size = %d scale = %d iv_stride = %d vect_size %d: ",
1025       mem_ref->_idx, offset, iv_adjustment, elt_size, scale, iv_stride(), vw);
1026     mem_ref->dump();
1027   }
1028 #endif
1029   return iv_adjustment;
1030 }
1031 
1032 //---------------------------dependence_graph---------------------------
1033 // Construct dependency graph.
1034 // Add dependence edges to load/store nodes for memory dependence
1035 //    A.out()->DependNode.in(1) and DependNode.out()->B.prec(x)
1036 void SuperWord::dependence_graph() {
1037   CountedLoopNode *cl = lpt()->_head->as_CountedLoop();
1038   // First, assign a dependence node to each memory node
1039   for (int i = 0; i < _block.length(); i++ ) {
1040     Node *n = _block.at(i);
1041     if (n->is_Mem() || (n->is_Phi() && n->bottom_type() == Type::MEMORY)) {
1042       _dg.make_node(n);
1043     }
1044   }
1045 
1046   // For each memory slice, create the dependences
1047   for (int i = 0; i < _mem_slice_head.length(); i++) {
1048     Node* n      = _mem_slice_head.at(i);
1049     Node* n_tail = _mem_slice_tail.at(i);
1050 
1051     // Get slice in predecessor order (last is first)
1052     if (cl->is_main_loop()) {
1053       mem_slice_preds(n_tail, n, _nlist);
1054     }
1055 
1056 #ifndef PRODUCT
1057     if(TraceSuperWord && Verbose) {
1058       tty->print_cr("SuperWord::dependence_graph: built a new mem slice");
1059       for (int j = _nlist.length() - 1; j >= 0 ; j--) {
1060         _nlist.at(j)->dump();
1061       }
1062     }
1063 #endif
1064     // Make the slice dependent on the root
1065     DepMem* slice = _dg.dep(n);
1066     _dg.make_edge(_dg.root(), slice);
1067 
1068     // Create a sink for the slice
1069     DepMem* slice_sink = _dg.make_node(NULL);
1070     _dg.make_edge(slice_sink, _dg.tail());
1071 
1072     // Now visit each pair of memory ops, creating the edges
1073     for (int j = _nlist.length() - 1; j >= 0 ; j--) {
1074       Node* s1 = _nlist.at(j);
1075 
1076       // If no dependency yet, use slice
1077       if (_dg.dep(s1)->in_cnt() == 0) {
1078         _dg.make_edge(slice, s1);
1079       }
1080       SWPointer p1(s1->as_Mem(), this, NULL, false);
1081       bool sink_dependent = true;
1082       for (int k = j - 1; k >= 0; k--) {
1083         Node* s2 = _nlist.at(k);
1084         if (s1->is_Load() && s2->is_Load())
1085           continue;
1086         SWPointer p2(s2->as_Mem(), this, NULL, false);
1087 
1088         int cmp = p1.cmp(p2);
1089         if (SuperWordRTDepCheck &&
1090             p1.base() != p2.base() && p1.valid() && p2.valid()) {
1091           // Create a runtime check to disambiguate
1092           OrderedPair pp(p1.base(), p2.base());
1093           _disjoint_ptrs.append_if_missing(pp);
1094         } else if (!SWPointer::not_equal(cmp)) {
1095           // Possibly same address
1096           _dg.make_edge(s1, s2);
1097           sink_dependent = false;
1098         }
1099       }
1100       if (sink_dependent) {
1101         _dg.make_edge(s1, slice_sink);
1102       }
1103     }
1104 
1105     if (TraceSuperWord) {
1106       tty->print_cr("\nDependence graph for slice: %d", n->_idx);
1107       for (int q = 0; q < _nlist.length(); q++) {
1108         _dg.print(_nlist.at(q));
1109       }
1110       tty->cr();
1111     }
1112 
1113     _nlist.clear();
1114   }
1115 
1116   if (TraceSuperWord) {
1117     tty->print_cr("\ndisjoint_ptrs: %s", _disjoint_ptrs.length() > 0 ? "" : "NONE");
1118     for (int r = 0; r < _disjoint_ptrs.length(); r++) {
1119       _disjoint_ptrs.at(r).print();
1120       tty->cr();
1121     }
1122     tty->cr();
1123   }
1124 
1125 }
1126 
1127 //---------------------------mem_slice_preds---------------------------
1128 // Return a memory slice (node list) in predecessor order starting at "start"
1129 void SuperWord::mem_slice_preds(Node* start, Node* stop, GrowableArray<Node*> &preds) {
1130   assert(preds.length() == 0, "start empty");
1131   Node* n = start;
1132   Node* prev = NULL;
1133   while (true) {
1134     NOT_PRODUCT( if(is_trace_mem_slice()) tty->print_cr("SuperWord::mem_slice_preds: n %d", n->_idx);)
1135     assert(in_bb(n), "must be in block");
1136     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1137       Node* out = n->fast_out(i);
1138       if (out->is_Load()) {
1139         if (in_bb(out)) {
1140           preds.push(out);
1141           if (TraceSuperWord && Verbose) {
1142             tty->print_cr("SuperWord::mem_slice_preds: added pred(%d)", out->_idx);
1143           }
1144         }
1145       } else {
1146         // FIXME
1147         if (out->is_MergeMem() && !in_bb(out)) {
1148           // Either unrolling is causing a memory edge not to disappear,
1149           // or need to run igvn.optimize() again before SLP
1150         } else if (out->is_Phi() && out->bottom_type() == Type::MEMORY && !in_bb(out)) {
1151           // Ditto.  Not sure what else to check further.
1152         } else if (out->Opcode() == Op_StoreCM && out->in(MemNode::OopStore) == n) {
1153           // StoreCM has an input edge used as a precedence edge.
1154           // Maybe an issue when oop stores are vectorized.
1155         } else {
1156           assert(out == prev || prev == NULL, "no branches off of store slice");
1157         }
1158       }//else
1159     }//for
1160     if (n == stop) break;
1161     preds.push(n);
1162     if (TraceSuperWord && Verbose) {
1163       tty->print_cr("SuperWord::mem_slice_preds: added pred(%d)", n->_idx);
1164     }
1165     prev = n;
1166     assert(n->is_Mem(), "unexpected node %s", n->Name());
1167     n = n->in(MemNode::Memory);
1168   }
1169 }
1170 
1171 //------------------------------stmts_can_pack---------------------------
1172 // Can s1 and s2 be in a pack with s1 immediately preceding s2 and
1173 // s1 aligned at "align"
1174 bool SuperWord::stmts_can_pack(Node* s1, Node* s2, int align) {
1175 
1176   // Do not use superword for non-primitives
1177   BasicType bt1 = velt_basic_type(s1);
1178   BasicType bt2 = velt_basic_type(s2);
1179   if(!is_java_primitive(bt1) || !is_java_primitive(bt2))
1180     return false;
1181   if (Matcher::max_vector_size(bt1) < 2) {
1182     return false; // No vectors for this type
1183   }
1184 
1185   if (isomorphic(s1, s2)) {
1186     if ((independent(s1, s2) && have_similar_inputs(s1, s2)) || reduction(s1, s2)) {
1187       if (!exists_at(s1, 0) && !exists_at(s2, 1)) {
1188         if (!s1->is_Mem() || are_adjacent_refs(s1, s2)) {
1189           int s1_align = alignment(s1);
1190           int s2_align = alignment(s2);
1191           if (s1_align == top_align || s1_align == align) {
1192             if (s2_align == top_align || s2_align == align + data_size(s1)) {
1193               return true;
1194             }
1195           }
1196         }
1197       }
1198     }
1199   }
1200   return false;
1201 }
1202 
1203 //------------------------------exists_at---------------------------
1204 // Does s exist in a pack at position pos?
1205 bool SuperWord::exists_at(Node* s, uint pos) {
1206   for (int i = 0; i < _packset.length(); i++) {
1207     Node_List* p = _packset.at(i);
1208     if (p->at(pos) == s) {
1209       return true;
1210     }
1211   }
1212   return false;
1213 }
1214 
1215 //------------------------------are_adjacent_refs---------------------------
1216 // Is s1 immediately before s2 in memory?
1217 bool SuperWord::are_adjacent_refs(Node* s1, Node* s2) {
1218   if (!s1->is_Mem() || !s2->is_Mem()) return false;
1219   if (!in_bb(s1)    || !in_bb(s2))    return false;
1220 
1221   // Do not use superword for non-primitives
1222   if (!is_java_primitive(s1->as_Mem()->memory_type()) ||
1223       !is_java_primitive(s2->as_Mem()->memory_type())) {
1224     return false;
1225   }
1226 
1227   // FIXME - co_locate_pack fails on Stores in different mem-slices, so
1228   // only pack memops that are in the same alias set until that's fixed.
1229   if (_phase->C->get_alias_index(s1->as_Mem()->adr_type()) !=
1230       _phase->C->get_alias_index(s2->as_Mem()->adr_type()))
1231     return false;
1232   SWPointer p1(s1->as_Mem(), this, NULL, false);
1233   SWPointer p2(s2->as_Mem(), this, NULL, false);
1234   if (p1.base() != p2.base() || !p1.comparable(p2)) return false;
1235   int diff = p2.offset_in_bytes() - p1.offset_in_bytes();
1236   return diff == data_size(s1);
1237 }
1238 
1239 //------------------------------isomorphic---------------------------
1240 // Are s1 and s2 similar?
1241 bool SuperWord::isomorphic(Node* s1, Node* s2) {
1242   if (s1->Opcode() != s2->Opcode()) return false;
1243   if (s1->req() != s2->req()) return false;
1244   if (!same_velt_type(s1, s2)) return false;
1245   Node* s1_ctrl = s1->in(0);
1246   Node* s2_ctrl = s2->in(0);
1247   // If the control nodes are equivalent, no further checks are required to test for isomorphism.
1248   if (s1_ctrl == s2_ctrl) {
1249     return true;
1250   } else {
1251     bool s1_ctrl_inv = ((s1_ctrl == NULL) ? true : lpt()->is_invariant(s1_ctrl));
1252     bool s2_ctrl_inv = ((s2_ctrl == NULL) ? true : lpt()->is_invariant(s2_ctrl));
1253     // If the control nodes are not invariant for the loop, fail isomorphism test.
1254     if (!s1_ctrl_inv || !s2_ctrl_inv) {
1255       return false;
1256     }
1257     if(s1_ctrl != NULL && s2_ctrl != NULL) {
1258       if (s1_ctrl->is_Proj()) {
1259         s1_ctrl = s1_ctrl->in(0);
1260         assert(lpt()->is_invariant(s1_ctrl), "must be invariant");
1261       }
1262       if (s2_ctrl->is_Proj()) {
1263         s2_ctrl = s2_ctrl->in(0);
1264         assert(lpt()->is_invariant(s2_ctrl), "must be invariant");
1265       }
1266       if (!s1_ctrl->is_RangeCheck() || !s2_ctrl->is_RangeCheck()) {
1267         return false;
1268       }
1269     }
1270     // Control nodes are invariant. However, we have no way of checking whether they resolve
1271     // in an equivalent manner. But, we know that invariant range checks are guaranteed to
1272     // throw before the loop (if they would have thrown). Thus, the loop would not have been reached.
1273     // Therefore, if the control nodes for both are range checks, we accept them to be isomorphic.
1274     for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
1275       Node* t1 = s1->fast_out(i);
1276       for (DUIterator_Fast jmax, j = s2->fast_outs(jmax); j < jmax; j++) {
1277         Node* t2 = s2->fast_out(j);
1278         if (VectorNode::is_muladds2i(t1) && VectorNode::is_muladds2i(t2)) {
1279           return true;
1280         }
1281       }
1282     }
1283   }
1284   return false;
1285 }
1286 
1287 //------------------------------independent---------------------------
1288 // Is there no data path from s1 to s2 or s2 to s1?
1289 bool SuperWord::independent(Node* s1, Node* s2) {
1290   //  assert(s1->Opcode() == s2->Opcode(), "check isomorphic first");
1291   int d1 = depth(s1);
1292   int d2 = depth(s2);
1293   if (d1 == d2) return s1 != s2;
1294   Node* deep    = d1 > d2 ? s1 : s2;
1295   Node* shallow = d1 > d2 ? s2 : s1;
1296 
1297   visited_clear();
1298 
1299   return independent_path(shallow, deep);
1300 }
1301 
1302 //--------------------------have_similar_inputs-----------------------
1303 // For a node pair (s1, s2) which is isomorphic and independent,
1304 // do s1 and s2 have similar input edges?
1305 bool SuperWord::have_similar_inputs(Node* s1, Node* s2) {
1306   // assert(isomorphic(s1, s2) == true, "check isomorphic");
1307   // assert(independent(s1, s2) == true, "check independent");
1308   if (s1->req() > 1 && !s1->is_Store() && !s1->is_Load()) {
1309     for (uint i = 1; i < s1->req(); i++) {
1310       if (s1->in(i)->Opcode() != s2->in(i)->Opcode()) return false;
1311     }
1312   }
1313   return true;
1314 }
1315 
1316 //------------------------------reduction---------------------------
1317 // Is there a data path between s1 and s2 and the nodes reductions?
1318 bool SuperWord::reduction(Node* s1, Node* s2) {
1319   bool retValue = false;
1320   int d1 = depth(s1);
1321   int d2 = depth(s2);
1322   if (d1 + 1 == d2) {
1323     if (s1->is_reduction() && s2->is_reduction()) {
1324       // This is an ordered set, so s1 should define s2
1325       for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
1326         Node* t1 = s1->fast_out(i);
1327         if (t1 == s2) {
1328           // both nodes are reductions and connected
1329           retValue = true;
1330         }
1331       }
1332     }
1333   }
1334 
1335   return retValue;
1336 }
1337 
1338 //------------------------------independent_path------------------------------
1339 // Helper for independent
1340 bool SuperWord::independent_path(Node* shallow, Node* deep, uint dp) {
1341   if (dp >= 1000) return false; // stop deep recursion
1342   visited_set(deep);
1343   int shal_depth = depth(shallow);
1344   assert(shal_depth <= depth(deep), "must be");
1345   for (DepPreds preds(deep, _dg); !preds.done(); preds.next()) {
1346     Node* pred = preds.current();
1347     if (in_bb(pred) && !visited_test(pred)) {
1348       if (shallow == pred) {
1349         return false;
1350       }
1351       if (shal_depth < depth(pred) && !independent_path(shallow, pred, dp+1)) {
1352         return false;
1353       }
1354     }
1355   }
1356   return true;
1357 }
1358 
1359 //------------------------------set_alignment---------------------------
1360 void SuperWord::set_alignment(Node* s1, Node* s2, int align) {
1361   set_alignment(s1, align);
1362   if (align == top_align || align == bottom_align) {
1363     set_alignment(s2, align);
1364   } else {
1365     set_alignment(s2, align + data_size(s1));
1366   }
1367 }
1368 
1369 //------------------------------data_size---------------------------
1370 int SuperWord::data_size(Node* s) {
1371   Node* use = NULL; //test if the node is a candidate for CMoveV optimization, then return the size of CMov
1372   if (UseVectorCmov) {
1373     use = _cmovev_kit.is_Bool_candidate(s);
1374     if (use != NULL) {
1375       return data_size(use);
1376     }
1377     use = _cmovev_kit.is_CmpD_candidate(s);
1378     if (use != NULL) {
1379       return data_size(use);
1380     }
1381   }
1382 
1383   int bsize = type2aelembytes(velt_basic_type(s));
1384   assert(bsize != 0, "valid size");
1385   return bsize;
1386 }
1387 
1388 //------------------------------extend_packlist---------------------------
1389 // Extend packset by following use->def and def->use links from pack members.
1390 void SuperWord::extend_packlist() {
1391   bool changed;
1392   do {
1393     packset_sort(_packset.length());
1394     changed = false;
1395     for (int i = 0; i < _packset.length(); i++) {
1396       Node_List* p = _packset.at(i);
1397       changed |= follow_use_defs(p);
1398       changed |= follow_def_uses(p);
1399     }
1400   } while (changed);
1401 
1402   if (_race_possible) {
1403     for (int i = 0; i < _packset.length(); i++) {
1404       Node_List* p = _packset.at(i);
1405       order_def_uses(p);
1406     }
1407   }
1408 
1409   if (TraceSuperWord) {
1410     tty->print_cr("\nAfter extend_packlist");
1411     print_packset();
1412   }
1413 }
1414 
1415 //------------------------------follow_use_defs---------------------------
1416 // Extend the packset by visiting operand definitions of nodes in pack p
1417 bool SuperWord::follow_use_defs(Node_List* p) {
1418   assert(p->size() == 2, "just checking");
1419   Node* s1 = p->at(0);
1420   Node* s2 = p->at(1);
1421   assert(s1->req() == s2->req(), "just checking");
1422   assert(alignment(s1) + data_size(s1) == alignment(s2), "just checking");
1423 
1424   if (s1->is_Load()) return false;
1425 
1426   int align = alignment(s1);
1427   NOT_PRODUCT(if(is_trace_alignment()) tty->print_cr("SuperWord::follow_use_defs: s1 %d, align %d", s1->_idx, align);)
1428   bool changed = false;
1429   int start = s1->is_Store() ? MemNode::ValueIn   : 1;
1430   int end   = s1->is_Store() ? MemNode::ValueIn+1 : s1->req();
1431   for (int j = start; j < end; j++) {
1432     Node* t1 = s1->in(j);
1433     Node* t2 = s2->in(j);
1434     if (!in_bb(t1) || !in_bb(t2))
1435       continue;
1436     if (stmts_can_pack(t1, t2, align)) {
1437       if (est_savings(t1, t2) >= 0) {
1438         Node_List* pair = new Node_List();
1439         pair->push(t1);
1440         pair->push(t2);
1441         _packset.append(pair);
1442         NOT_PRODUCT(if(is_trace_alignment()) tty->print_cr("SuperWord::follow_use_defs: set_alignment(%d, %d, %d)", t1->_idx, t2->_idx, align);)
1443         set_alignment(t1, t2, align);
1444         changed = true;
1445       }
1446     }
1447   }
1448   return changed;
1449 }
1450 
1451 //------------------------------follow_def_uses---------------------------
1452 // Extend the packset by visiting uses of nodes in pack p
1453 bool SuperWord::follow_def_uses(Node_List* p) {
1454   bool changed = false;
1455   Node* s1 = p->at(0);
1456   Node* s2 = p->at(1);
1457   assert(p->size() == 2, "just checking");
1458   assert(s1->req() == s2->req(), "just checking");
1459   assert(alignment(s1) + data_size(s1) == alignment(s2), "just checking");
1460 
1461   if (s1->is_Store()) return false;
1462 
1463   int align = alignment(s1);
1464   NOT_PRODUCT(if(is_trace_alignment()) tty->print_cr("SuperWord::follow_def_uses: s1 %d, align %d", s1->_idx, align);)
1465   int savings = -1;
1466   int num_s1_uses = 0;
1467   Node* u1 = NULL;
1468   Node* u2 = NULL;
1469   for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
1470     Node* t1 = s1->fast_out(i);
1471     num_s1_uses++;
1472     if (!in_bb(t1)) continue;
1473     for (DUIterator_Fast jmax, j = s2->fast_outs(jmax); j < jmax; j++) {
1474       Node* t2 = s2->fast_out(j);
1475       if (!in_bb(t2)) continue;
1476       if (t2->Opcode() == Op_AddI && t2 == _lp->as_CountedLoop()->incr()) continue; // don't mess with the iv
1477       if (!opnd_positions_match(s1, t1, s2, t2))
1478         continue;
1479       if (stmts_can_pack(t1, t2, align)) {
1480         int my_savings = est_savings(t1, t2);
1481         if (my_savings > savings) {
1482           savings = my_savings;
1483           u1 = t1;
1484           u2 = t2;
1485         }
1486       }
1487     }
1488   }
1489   if (num_s1_uses > 1) {
1490     _race_possible = true;
1491   }
1492   if (savings >= 0) {
1493     Node_List* pair = new Node_List();
1494     pair->push(u1);
1495     pair->push(u2);
1496     _packset.append(pair);
1497     NOT_PRODUCT(if(is_trace_alignment()) tty->print_cr("SuperWord::follow_def_uses: set_alignment(%d, %d, %d)", u1->_idx, u2->_idx, align);)
1498     set_alignment(u1, u2, align);
1499     changed = true;
1500   }
1501   return changed;
1502 }
1503 
1504 //------------------------------order_def_uses---------------------------
1505 // For extended packsets, ordinally arrange uses packset by major component
1506 void SuperWord::order_def_uses(Node_List* p) {
1507   Node* s1 = p->at(0);
1508 
1509   if (s1->is_Store()) return;
1510 
1511   // reductions are always managed beforehand
1512   if (s1->is_reduction()) return;
1513 
1514   for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
1515     Node* t1 = s1->fast_out(i);
1516 
1517     // Only allow operand swap on commuting operations
1518     if (!t1->is_Add() && !t1->is_Mul() && !VectorNode::is_muladds2i(t1)) {
1519       break;
1520     }
1521 
1522     // Now find t1's packset
1523     Node_List* p2 = NULL;
1524     for (int j = 0; j < _packset.length(); j++) {
1525       p2 = _packset.at(j);
1526       Node* first = p2->at(0);
1527       if (t1 == first) {
1528         break;
1529       }
1530       p2 = NULL;
1531     }
1532     // Arrange all sub components by the major component
1533     if (p2 != NULL) {
1534       for (uint j = 1; j < p->size(); j++) {
1535         Node* d1 = p->at(j);
1536         Node* u1 = p2->at(j);
1537         opnd_positions_match(s1, t1, d1, u1);
1538       }
1539     }
1540   }
1541 }
1542 
1543 //---------------------------opnd_positions_match-------------------------
1544 // Is the use of d1 in u1 at the same operand position as d2 in u2?
1545 bool SuperWord::opnd_positions_match(Node* d1, Node* u1, Node* d2, Node* u2) {
1546   // check reductions to see if they are marshalled to represent the reduction
1547   // operator in a specified opnd
1548   if (u1->is_reduction() && u2->is_reduction()) {
1549     // ensure reductions have phis and reduction definitions feeding the 1st operand
1550     Node* first = u1->in(2);
1551     if (first->is_Phi() || first->is_reduction()) {
1552       u1->swap_edges(1, 2);
1553     }
1554     // ensure reductions have phis and reduction definitions feeding the 1st operand
1555     first = u2->in(2);
1556     if (first->is_Phi() || first->is_reduction()) {
1557       u2->swap_edges(1, 2);
1558     }
1559     return true;
1560   }
1561 
1562   uint ct = u1->req();
1563   if (ct != u2->req()) return false;
1564   uint i1 = 0;
1565   uint i2 = 0;
1566   do {
1567     for (i1++; i1 < ct; i1++) if (u1->in(i1) == d1) break;
1568     for (i2++; i2 < ct; i2++) if (u2->in(i2) == d2) break;
1569     if (i1 != i2) {
1570       if ((i1 == (3-i2)) && (u2->is_Add() || u2->is_Mul())) {
1571         // Further analysis relies on operands position matching.
1572         u2->swap_edges(i1, i2);
1573       } else if (VectorNode::is_muladds2i(u2) && u1 != u2) {
1574         if (i1 == 5 - i2) { // ((i1 == 3 && i2 == 2) || (i1 == 2 && i2 == 3) || (i1 == 1 && i2 == 4) || (i1 == 4 && i2 == 1))
1575           u2->swap_edges(1, 2);
1576           u2->swap_edges(3, 4);
1577         }
1578         if (i1 == 3 - i2 || i1 == 7 - i2) { // ((i1 == 1 && i2 == 2) || (i1 == 2 && i2 == 1) || (i1 == 3 && i2 == 4) || (i1 == 4 && i2 == 3))
1579           u2->swap_edges(2, 3);
1580           u2->swap_edges(1, 4);
1581         }
1582         return false; // Just swap the edges, the muladds2i nodes get packed in follow_use_defs
1583       } else {
1584         return false;
1585       }
1586     } else if (i1 == i2 && VectorNode::is_muladds2i(u2) && u1 != u2) {
1587       u2->swap_edges(1, 3);
1588       u2->swap_edges(2, 4);
1589       return false; // Just swap the edges, the muladds2i nodes get packed in follow_use_defs
1590     }
1591   } while (i1 < ct);
1592   return true;
1593 }
1594 
1595 //------------------------------est_savings---------------------------
1596 // Estimate the savings from executing s1 and s2 as a pack
1597 int SuperWord::est_savings(Node* s1, Node* s2) {
1598   int save_in = 2 - 1; // 2 operations per instruction in packed form
1599 
1600   // inputs
1601   for (uint i = 1; i < s1->req(); i++) {
1602     Node* x1 = s1->in(i);
1603     Node* x2 = s2->in(i);
1604     if (x1 != x2) {
1605       if (are_adjacent_refs(x1, x2)) {
1606         save_in += adjacent_profit(x1, x2);
1607       } else if (!in_packset(x1, x2)) {
1608         save_in -= pack_cost(2);
1609       } else {
1610         save_in += unpack_cost(2);
1611       }
1612     }
1613   }
1614 
1615   // uses of result
1616   uint ct = 0;
1617   int save_use = 0;
1618   for (DUIterator_Fast imax, i = s1->fast_outs(imax); i < imax; i++) {
1619     Node* s1_use = s1->fast_out(i);
1620     for (int j = 0; j < _packset.length(); j++) {
1621       Node_List* p = _packset.at(j);
1622       if (p->at(0) == s1_use) {
1623         for (DUIterator_Fast kmax, k = s2->fast_outs(kmax); k < kmax; k++) {
1624           Node* s2_use = s2->fast_out(k);
1625           if (p->at(p->size()-1) == s2_use) {
1626             ct++;
1627             if (are_adjacent_refs(s1_use, s2_use)) {
1628               save_use += adjacent_profit(s1_use, s2_use);
1629             }
1630           }
1631         }
1632       }
1633     }
1634   }
1635 
1636   if (ct < s1->outcnt()) save_use += unpack_cost(1);
1637   if (ct < s2->outcnt()) save_use += unpack_cost(1);
1638 
1639   return MAX2(save_in, save_use);
1640 }
1641 
1642 //------------------------------costs---------------------------
1643 int SuperWord::adjacent_profit(Node* s1, Node* s2) { return 2; }
1644 int SuperWord::pack_cost(int ct)   { return ct; }
1645 int SuperWord::unpack_cost(int ct) { return ct; }
1646 
1647 //------------------------------combine_packs---------------------------
1648 // Combine packs A and B with A.last == B.first into A.first..,A.last,B.second,..B.last
1649 void SuperWord::combine_packs() {
1650   bool changed = true;
1651   // Combine packs regardless max vector size.
1652   while (changed) {
1653     changed = false;
1654     for (int i = 0; i < _packset.length(); i++) {
1655       Node_List* p1 = _packset.at(i);
1656       if (p1 == NULL) continue;
1657       // Because of sorting we can start at i + 1
1658       for (int j = i + 1; j < _packset.length(); j++) {
1659         Node_List* p2 = _packset.at(j);
1660         if (p2 == NULL) continue;
1661         if (i == j) continue;
1662         if (p1->at(p1->size()-1) == p2->at(0)) {
1663           for (uint k = 1; k < p2->size(); k++) {
1664             p1->push(p2->at(k));
1665           }
1666           _packset.at_put(j, NULL);
1667           changed = true;
1668         }
1669       }
1670     }
1671   }
1672 
1673   // Split packs which have size greater then max vector size.
1674   for (int i = 0; i < _packset.length(); i++) {
1675     Node_List* p1 = _packset.at(i);
1676     if (p1 != NULL) {
1677       BasicType bt = velt_basic_type(p1->at(0));
1678       uint max_vlen = Matcher::max_vector_size(bt); // Max elements in vector
1679       assert(is_power_of_2(max_vlen), "sanity");
1680       uint psize = p1->size();
1681       if (!is_power_of_2(psize)) {
1682         // Skip pack which can't be vector.
1683         // case1: for(...) { a[i] = i; }    elements values are different (i+x)
1684         // case2: for(...) { a[i] = b[i+1]; }  can't align both, load and store
1685         _packset.at_put(i, NULL);
1686         continue;
1687       }
1688       if (psize > max_vlen) {
1689         Node_List* pack = new Node_List();
1690         for (uint j = 0; j < psize; j++) {
1691           pack->push(p1->at(j));
1692           if (pack->size() >= max_vlen) {
1693             assert(is_power_of_2(pack->size()), "sanity");
1694             _packset.append(pack);
1695             pack = new Node_List();
1696           }
1697         }
1698         _packset.at_put(i, NULL);
1699       }
1700     }
1701   }
1702 
1703   // Compress list.
1704   for (int i = _packset.length() - 1; i >= 0; i--) {
1705     Node_List* p1 = _packset.at(i);
1706     if (p1 == NULL) {
1707       _packset.remove_at(i);
1708     }
1709   }
1710 
1711   if (TraceSuperWord) {
1712     tty->print_cr("\nAfter combine_packs");
1713     print_packset();
1714   }
1715 }
1716 
1717 //-----------------------------construct_my_pack_map--------------------------
1718 // Construct the map from nodes to packs.  Only valid after the
1719 // point where a node is only in one pack (after combine_packs).
1720 void SuperWord::construct_my_pack_map() {
1721   Node_List* rslt = NULL;
1722   for (int i = 0; i < _packset.length(); i++) {
1723     Node_List* p = _packset.at(i);
1724     for (uint j = 0; j < p->size(); j++) {
1725       Node* s = p->at(j);
1726       assert(my_pack(s) == NULL, "only in one pack");
1727       set_my_pack(s, p);
1728     }
1729   }
1730 }
1731 
1732 //------------------------------filter_packs---------------------------
1733 // Remove packs that are not implemented or not profitable.
1734 void SuperWord::filter_packs() {
1735   // Remove packs that are not implemented
1736   for (int i = _packset.length() - 1; i >= 0; i--) {
1737     Node_List* pk = _packset.at(i);
1738     bool impl = implemented(pk);
1739     if (!impl) {
1740 #ifndef PRODUCT
1741       if (TraceSuperWord && Verbose) {
1742         tty->print_cr("Unimplemented");
1743         pk->at(0)->dump();
1744       }
1745 #endif
1746       remove_pack_at(i);
1747     }
1748     Node *n = pk->at(0);
1749     if (n->is_reduction()) {
1750       _num_reductions++;
1751     } else {
1752       _num_work_vecs++;
1753     }
1754   }
1755 
1756   // Remove packs that are not profitable
1757   bool changed;
1758   do {
1759     changed = false;
1760     for (int i = _packset.length() - 1; i >= 0; i--) {
1761       Node_List* pk = _packset.at(i);
1762       bool prof = profitable(pk);
1763       if (!prof) {
1764 #ifndef PRODUCT
1765         if (TraceSuperWord && Verbose) {
1766           tty->print_cr("Unprofitable");
1767           pk->at(0)->dump();
1768         }
1769 #endif
1770         remove_pack_at(i);
1771         changed = true;
1772       }
1773     }
1774   } while (changed);
1775 
1776 #ifndef PRODUCT
1777   if (TraceSuperWord) {
1778     tty->print_cr("\nAfter filter_packs");
1779     print_packset();
1780     tty->cr();
1781   }
1782 #endif
1783 }
1784 
1785 //------------------------------merge_packs_to_cmovd---------------------------
1786 // Merge CMoveD into new vector-nodes
1787 // We want to catch this pattern and subsume CmpD and Bool into CMoveD
1788 //
1789 //                   SubD             ConD
1790 //                  /  |               /
1791 //                 /   |           /   /
1792 //                /    |       /      /
1793 //               /     |   /         /
1794 //              /      /            /
1795 //             /    /  |           /
1796 //            v /      |          /
1797 //         CmpD        |         /
1798 //          |          |        /
1799 //          v          |       /
1800 //         Bool        |      /
1801 //           \         |     /
1802 //             \       |    /
1803 //               \     |   /
1804 //                 \   |  /
1805 //                   \ v /
1806 //                   CMoveD
1807 //
1808 
1809 void SuperWord::merge_packs_to_cmovd() {
1810   for (int i = _packset.length() - 1; i >= 0; i--) {
1811     _cmovev_kit.make_cmovevd_pack(_packset.at(i));
1812   }
1813   #ifndef PRODUCT
1814     if (TraceSuperWord) {
1815       tty->print_cr("\nSuperWord::merge_packs_to_cmovd(): After merge");
1816       print_packset();
1817       tty->cr();
1818     }
1819   #endif
1820 }
1821 
1822 Node* CMoveKit::is_Bool_candidate(Node* def) const {
1823   Node* use = NULL;
1824   if (!def->is_Bool() || def->in(0) != NULL || def->outcnt() != 1) {
1825     return NULL;
1826   }
1827   for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
1828     use = def->fast_out(j);
1829     if (!_sw->same_generation(def, use) || !use->is_CMove()) {
1830       return NULL;
1831     }
1832   }
1833   return use;
1834 }
1835 
1836 Node* CMoveKit::is_CmpD_candidate(Node* def) const {
1837   Node* use = NULL;
1838   if (!def->is_Cmp() || def->in(0) != NULL || def->outcnt() != 1) {
1839     return NULL;
1840   }
1841   for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
1842     use = def->fast_out(j);
1843     if (!_sw->same_generation(def, use) || (use = is_Bool_candidate(use)) == NULL || !_sw->same_generation(def, use)) {
1844       return NULL;
1845     }
1846   }
1847   return use;
1848 }
1849 
1850 Node_List* CMoveKit::make_cmovevd_pack(Node_List* cmovd_pk) {
1851   Node *cmovd = cmovd_pk->at(0);
1852   if (!cmovd->is_CMove()) {
1853     return NULL;
1854   }
1855   if (cmovd->Opcode() != Op_CMoveF && cmovd->Opcode() != Op_CMoveD) {
1856     return NULL;
1857   }
1858   if (pack(cmovd) != NULL) { // already in the cmov pack
1859     return NULL;
1860   }
1861   if (cmovd->in(0) != NULL) {
1862     NOT_PRODUCT(if(_sw->is_trace_cmov()) {tty->print("CMoveKit::make_cmovevd_pack: CMoveD %d has control flow, escaping...", cmovd->_idx); cmovd->dump();})
1863     return NULL;
1864   }
1865 
1866   Node* bol = cmovd->as_CMove()->in(CMoveNode::Condition);
1867   if (!bol->is_Bool()
1868       || bol->outcnt() != 1
1869       || !_sw->same_generation(bol, cmovd)
1870       || bol->in(0) != NULL  // BoolNode has control flow!!
1871       || _sw->my_pack(bol) == NULL) {
1872       NOT_PRODUCT(if(_sw->is_trace_cmov()) {tty->print("CMoveKit::make_cmovevd_pack: Bool %d does not fit CMoveD %d for building vector, escaping...", bol->_idx, cmovd->_idx); bol->dump();})
1873       return NULL;
1874   }
1875   Node_List* bool_pk = _sw->my_pack(bol);
1876   if (bool_pk->size() != cmovd_pk->size() ) {
1877     return NULL;
1878   }
1879 
1880   Node* cmpd = bol->in(1);
1881   if (!cmpd->is_Cmp()
1882       || cmpd->outcnt() != 1
1883       || !_sw->same_generation(cmpd, cmovd)
1884       || cmpd->in(0) != NULL  // CmpDNode has control flow!!
1885       || _sw->my_pack(cmpd) == NULL) {
1886       NOT_PRODUCT(if(_sw->is_trace_cmov()) {tty->print("CMoveKit::make_cmovevd_pack: CmpD %d does not fit CMoveD %d for building vector, escaping...", cmpd->_idx, cmovd->_idx); cmpd->dump();})
1887       return NULL;
1888   }
1889   Node_List* cmpd_pk = _sw->my_pack(cmpd);
1890   if (cmpd_pk->size() != cmovd_pk->size() ) {
1891     return NULL;
1892   }
1893 
1894   if (!test_cmpd_pack(cmpd_pk, cmovd_pk)) {
1895     NOT_PRODUCT(if(_sw->is_trace_cmov()) {tty->print("CMoveKit::make_cmovevd_pack: cmpd pack for CmpD %d failed vectorization test", cmpd->_idx); cmpd->dump();})
1896     return NULL;
1897   }
1898 
1899   Node_List* new_cmpd_pk = new Node_List();
1900   uint sz = cmovd_pk->size() - 1;
1901   for (uint i = 0; i <= sz; ++i) {
1902     Node* cmov = cmovd_pk->at(i);
1903     Node* bol  = bool_pk->at(i);
1904     Node* cmp  = cmpd_pk->at(i);
1905 
1906     new_cmpd_pk->insert(i, cmov);
1907 
1908     map(cmov, new_cmpd_pk);
1909     map(bol, new_cmpd_pk);
1910     map(cmp, new_cmpd_pk);
1911 
1912     _sw->set_my_pack(cmov, new_cmpd_pk); // and keep old packs for cmp and bool
1913   }
1914   _sw->_packset.remove(cmovd_pk);
1915   _sw->_packset.remove(bool_pk);
1916   _sw->_packset.remove(cmpd_pk);
1917   _sw->_packset.append(new_cmpd_pk);
1918   NOT_PRODUCT(if(_sw->is_trace_cmov()) {tty->print_cr("CMoveKit::make_cmovevd_pack: added syntactic CMoveD pack"); _sw->print_pack(new_cmpd_pk);})
1919   return new_cmpd_pk;
1920 }
1921 
1922 bool CMoveKit::test_cmpd_pack(Node_List* cmpd_pk, Node_List* cmovd_pk) {
1923   Node* cmpd0 = cmpd_pk->at(0);
1924   assert(cmpd0->is_Cmp(), "CMoveKit::test_cmpd_pack: should be CmpDNode");
1925   assert(cmovd_pk->at(0)->is_CMove(), "CMoveKit::test_cmpd_pack: should be CMoveD");
1926   assert(cmpd_pk->size() == cmovd_pk->size(), "CMoveKit::test_cmpd_pack: should be same size");
1927   Node* in1 = cmpd0->in(1);
1928   Node* in2 = cmpd0->in(2);
1929   Node_List* in1_pk = _sw->my_pack(in1);
1930   Node_List* in2_pk = _sw->my_pack(in2);
1931 
1932   if (  (in1_pk != NULL && in1_pk->size() != cmpd_pk->size())
1933      || (in2_pk != NULL && in2_pk->size() != cmpd_pk->size()) ) {
1934     return false;
1935   }
1936 
1937   // test if "all" in1 are in the same pack or the same node
1938   if (in1_pk == NULL) {
1939     for (uint j = 1; j < cmpd_pk->size(); j++) {
1940       if (cmpd_pk->at(j)->in(1) != in1) {
1941         return false;
1942       }
1943     }//for: in1_pk is not pack but all CmpD nodes in the pack have the same in(1)
1944   }
1945   // test if "all" in2 are in the same pack or the same node
1946   if (in2_pk == NULL) {
1947     for (uint j = 1; j < cmpd_pk->size(); j++) {
1948       if (cmpd_pk->at(j)->in(2) != in2) {
1949         return false;
1950       }
1951     }//for: in2_pk is not pack but all CmpD nodes in the pack have the same in(2)
1952   }
1953   //now check if cmpd_pk may be subsumed in vector built for cmovd_pk
1954   int cmovd_ind1, cmovd_ind2;
1955   if (cmpd_pk->at(0)->in(1) == cmovd_pk->at(0)->as_CMove()->in(CMoveNode::IfFalse)
1956    && cmpd_pk->at(0)->in(2) == cmovd_pk->at(0)->as_CMove()->in(CMoveNode::IfTrue)) {
1957       cmovd_ind1 = CMoveNode::IfFalse;
1958       cmovd_ind2 = CMoveNode::IfTrue;
1959   } else if (cmpd_pk->at(0)->in(2) == cmovd_pk->at(0)->as_CMove()->in(CMoveNode::IfFalse)
1960           && cmpd_pk->at(0)->in(1) == cmovd_pk->at(0)->as_CMove()->in(CMoveNode::IfTrue)) {
1961       cmovd_ind2 = CMoveNode::IfFalse;
1962       cmovd_ind1 = CMoveNode::IfTrue;
1963   }
1964   else {
1965     return false;
1966   }
1967 
1968   for (uint j = 1; j < cmpd_pk->size(); j++) {
1969     if (cmpd_pk->at(j)->in(1) != cmovd_pk->at(j)->as_CMove()->in(cmovd_ind1)
1970         || cmpd_pk->at(j)->in(2) != cmovd_pk->at(j)->as_CMove()->in(cmovd_ind2)) {
1971         return false;
1972     }//if
1973   }
1974   NOT_PRODUCT(if(_sw->is_trace_cmov()) { tty->print("CMoveKit::test_cmpd_pack: cmpd pack for 1st CmpD %d is OK for vectorization: ", cmpd0->_idx); cmpd0->dump(); })
1975   return true;
1976 }
1977 
1978 //------------------------------implemented---------------------------
1979 // Can code be generated for pack p?
1980 bool SuperWord::implemented(Node_List* p) {
1981   bool retValue = false;
1982   Node* p0 = p->at(0);
1983   if (p0 != NULL) {
1984     int opc = p0->Opcode();
1985     uint size = p->size();
1986     if (p0->is_reduction()) {
1987       const Type *arith_type = p0->bottom_type();
1988       // Length 2 reductions of INT/LONG do not offer performance benefits
1989       if (((arith_type->basic_type() == T_INT) || (arith_type->basic_type() == T_LONG)) && (size == 2)) {
1990         retValue = false;
1991       } else {
1992         retValue = ReductionNode::implemented(opc, size, arith_type->basic_type());
1993       }
1994     } else {
1995       retValue = VectorNode::implemented(opc, size, velt_basic_type(p0));
1996     }
1997     if (!retValue) {
1998       if (is_cmov_pack(p)) {
1999         NOT_PRODUCT(if(is_trace_cmov()) {tty->print_cr("SWPointer::implemented: found cmpd pack"); print_pack(p);})
2000         return true;
2001       }
2002     }
2003   }
2004   return retValue;
2005 }
2006 
2007 bool SuperWord::is_cmov_pack(Node_List* p) {
2008   return _cmovev_kit.pack(p->at(0)) != NULL;
2009 }
2010 //------------------------------same_inputs--------------------------
2011 // For pack p, are all idx operands the same?
2012 bool SuperWord::same_inputs(Node_List* p, int idx) {
2013   Node* p0 = p->at(0);
2014   uint vlen = p->size();
2015   Node* p0_def = p0->in(idx);
2016   for (uint i = 1; i < vlen; i++) {
2017     Node* pi = p->at(i);
2018     Node* pi_def = pi->in(idx);
2019     if (p0_def != pi_def) {
2020       return false;
2021     }
2022   }
2023   return true;
2024 }
2025 
2026 //------------------------------profitable---------------------------
2027 // For pack p, are all operands and all uses (with in the block) vector?
2028 bool SuperWord::profitable(Node_List* p) {
2029   Node* p0 = p->at(0);
2030   uint start, end;
2031   VectorNode::vector_operands(p0, &start, &end);
2032 
2033   // Return false if some inputs are not vectors or vectors with different
2034   // size or alignment.
2035   // Also, for now, return false if not scalar promotion case when inputs are
2036   // the same. Later, implement PackNode and allow differing, non-vector inputs
2037   // (maybe just the ones from outside the block.)
2038   for (uint i = start; i < end; i++) {
2039     if (!is_vector_use(p0, i)) {
2040       return false;
2041     }
2042   }
2043   // Check if reductions are connected
2044   if (p0->is_reduction()) {
2045     Node* second_in = p0->in(2);
2046     Node_List* second_pk = my_pack(second_in);
2047     if ((second_pk == NULL) || (_num_work_vecs == _num_reductions)) {
2048       // Remove reduction flag if no parent pack or if not enough work
2049       // to cover reduction expansion overhead
2050       p0->remove_flag(Node::Flag_is_reduction);
2051       return false;
2052     } else if (second_pk->size() != p->size()) {
2053       return false;
2054     }
2055   }
2056   if (VectorNode::is_shift(p0)) {
2057     // For now, return false if shift count is vector or not scalar promotion
2058     // case (different shift counts) because it is not supported yet.
2059     Node* cnt = p0->in(2);
2060     Node_List* cnt_pk = my_pack(cnt);
2061     if (cnt_pk != NULL)
2062       return false;
2063     if (!same_inputs(p, 2))
2064       return false;
2065   }
2066   if (!p0->is_Store()) {
2067     // For now, return false if not all uses are vector.
2068     // Later, implement ExtractNode and allow non-vector uses (maybe
2069     // just the ones outside the block.)
2070     for (uint i = 0; i < p->size(); i++) {
2071       Node* def = p->at(i);
2072       if (is_cmov_pack_internal_node(p, def)) {
2073         continue;
2074       }
2075       for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
2076         Node* use = def->fast_out(j);
2077         for (uint k = 0; k < use->req(); k++) {
2078           Node* n = use->in(k);
2079           if (def == n) {
2080             // Reductions should only have a Phi use at the loop head or a non-phi use
2081             // outside of the loop if it is the last element of the pack (e.g. SafePoint).
2082             if (def->is_reduction() &&
2083                 ((use->is_Phi() && use->in(0) == _lpt->_head) ||
2084                  (!_lpt->is_member(_phase->get_loop(_phase->ctrl_or_self(use))) && i == p->size()-1))) {
2085               continue;
2086             }
2087             if (!is_vector_use(use, k)) {
2088               return false;
2089             }
2090           }
2091         }
2092       }
2093     }
2094   }
2095   return true;
2096 }
2097 
2098 //------------------------------schedule---------------------------
2099 // Adjust the memory graph for the packed operations
2100 void SuperWord::schedule() {
2101 
2102   // Co-locate in the memory graph the members of each memory pack
2103   for (int i = 0; i < _packset.length(); i++) {
2104     co_locate_pack(_packset.at(i));
2105   }
2106 }
2107 
2108 //-------------------------------remove_and_insert-------------------
2109 // Remove "current" from its current position in the memory graph and insert
2110 // it after the appropriate insertion point (lip or uip).
2111 void SuperWord::remove_and_insert(MemNode *current, MemNode *prev, MemNode *lip,
2112                                   Node *uip, Unique_Node_List &sched_before) {
2113   Node* my_mem = current->in(MemNode::Memory);
2114   bool sched_up = sched_before.member(current);
2115 
2116   // remove current_store from its current position in the memmory graph
2117   for (DUIterator i = current->outs(); current->has_out(i); i++) {
2118     Node* use = current->out(i);
2119     if (use->is_Mem()) {
2120       assert(use->in(MemNode::Memory) == current, "must be");
2121       if (use == prev) { // connect prev to my_mem
2122           _igvn.replace_input_of(use, MemNode::Memory, my_mem);
2123           --i; //deleted this edge; rescan position
2124       } else if (sched_before.member(use)) {
2125         if (!sched_up) { // Will be moved together with current
2126           _igvn.replace_input_of(use, MemNode::Memory, uip);
2127           --i; //deleted this edge; rescan position
2128         }
2129       } else {
2130         if (sched_up) { // Will be moved together with current
2131           _igvn.replace_input_of(use, MemNode::Memory, lip);
2132           --i; //deleted this edge; rescan position
2133         }
2134       }
2135     }
2136   }
2137 
2138   Node *insert_pt =  sched_up ?  uip : lip;
2139 
2140   // all uses of insert_pt's memory state should use current's instead
2141   for (DUIterator i = insert_pt->outs(); insert_pt->has_out(i); i++) {
2142     Node* use = insert_pt->out(i);
2143     if (use->is_Mem()) {
2144       assert(use->in(MemNode::Memory) == insert_pt, "must be");
2145       _igvn.replace_input_of(use, MemNode::Memory, current);
2146       --i; //deleted this edge; rescan position
2147     } else if (!sched_up && use->is_Phi() && use->bottom_type() == Type::MEMORY) {
2148       uint pos; //lip (lower insert point) must be the last one in the memory slice
2149       for (pos=1; pos < use->req(); pos++) {
2150         if (use->in(pos) == insert_pt) break;
2151       }
2152       _igvn.replace_input_of(use, pos, current);
2153       --i;
2154     }
2155   }
2156 
2157   //connect current to insert_pt
2158   _igvn.replace_input_of(current, MemNode::Memory, insert_pt);
2159 }
2160 
2161 //------------------------------co_locate_pack----------------------------------
2162 // To schedule a store pack, we need to move any sandwiched memory ops either before
2163 // or after the pack, based upon dependence information:
2164 // (1) If any store in the pack depends on the sandwiched memory op, the
2165 //     sandwiched memory op must be scheduled BEFORE the pack;
2166 // (2) If a sandwiched memory op depends on any store in the pack, the
2167 //     sandwiched memory op must be scheduled AFTER the pack;
2168 // (3) If a sandwiched memory op (say, memA) depends on another sandwiched
2169 //     memory op (say memB), memB must be scheduled before memA. So, if memA is
2170 //     scheduled before the pack, memB must also be scheduled before the pack;
2171 // (4) If there is no dependence restriction for a sandwiched memory op, we simply
2172 //     schedule this store AFTER the pack
2173 // (5) We know there is no dependence cycle, so there in no other case;
2174 // (6) Finally, all memory ops in another single pack should be moved in the same direction.
2175 //
2176 // To schedule a load pack, we use the memory state of either the first or the last load in
2177 // the pack, based on the dependence constraint.
2178 void SuperWord::co_locate_pack(Node_List* pk) {
2179   if (pk->at(0)->is_Store()) {
2180     MemNode* first     = executed_first(pk)->as_Mem();
2181     MemNode* last      = executed_last(pk)->as_Mem();
2182     Unique_Node_List schedule_before_pack;
2183     Unique_Node_List memops;
2184 
2185     MemNode* current   = last->in(MemNode::Memory)->as_Mem();
2186     MemNode* previous  = last;
2187     while (true) {
2188       assert(in_bb(current), "stay in block");
2189       memops.push(previous);
2190       for (DUIterator i = current->outs(); current->has_out(i); i++) {
2191         Node* use = current->out(i);
2192         if (use->is_Mem() && use != previous)
2193           memops.push(use);
2194       }
2195       if (current == first) break;
2196       previous = current;
2197       current  = current->in(MemNode::Memory)->as_Mem();
2198     }
2199 
2200     // determine which memory operations should be scheduled before the pack
2201     for (uint i = 1; i < memops.size(); i++) {
2202       Node *s1 = memops.at(i);
2203       if (!in_pack(s1, pk) && !schedule_before_pack.member(s1)) {
2204         for (uint j = 0; j< i; j++) {
2205           Node *s2 = memops.at(j);
2206           if (!independent(s1, s2)) {
2207             if (in_pack(s2, pk) || schedule_before_pack.member(s2)) {
2208               schedule_before_pack.push(s1); // s1 must be scheduled before
2209               Node_List* mem_pk = my_pack(s1);
2210               if (mem_pk != NULL) {
2211                 for (uint ii = 0; ii < mem_pk->size(); ii++) {
2212                   Node* s = mem_pk->at(ii);  // follow partner
2213                   if (memops.member(s) && !schedule_before_pack.member(s))
2214                     schedule_before_pack.push(s);
2215                 }
2216               }
2217               break;
2218             }
2219           }
2220         }
2221       }
2222     }
2223 
2224     Node*    upper_insert_pt = first->in(MemNode::Memory);
2225     // Following code moves loads connected to upper_insert_pt below aliased stores.
2226     // Collect such loads here and reconnect them back to upper_insert_pt later.
2227     memops.clear();
2228     for (DUIterator i = upper_insert_pt->outs(); upper_insert_pt->has_out(i); i++) {
2229       Node* use = upper_insert_pt->out(i);
2230       if (use->is_Mem() && !use->is_Store()) {
2231         memops.push(use);
2232       }
2233     }
2234 
2235     MemNode* lower_insert_pt = last;
2236     previous                 = last; //previous store in pk
2237     current                  = last->in(MemNode::Memory)->as_Mem();
2238 
2239     // start scheduling from "last" to "first"
2240     while (true) {
2241       assert(in_bb(current), "stay in block");
2242       assert(in_pack(previous, pk), "previous stays in pack");
2243       Node* my_mem = current->in(MemNode::Memory);
2244 
2245       if (in_pack(current, pk)) {
2246         // Forward users of my memory state (except "previous) to my input memory state
2247         for (DUIterator i = current->outs(); current->has_out(i); i++) {
2248           Node* use = current->out(i);
2249           if (use->is_Mem() && use != previous) {
2250             assert(use->in(MemNode::Memory) == current, "must be");
2251             if (schedule_before_pack.member(use)) {
2252               _igvn.replace_input_of(use, MemNode::Memory, upper_insert_pt);
2253             } else {
2254               _igvn.replace_input_of(use, MemNode::Memory, lower_insert_pt);
2255             }
2256             --i; // deleted this edge; rescan position
2257           }
2258         }
2259         previous = current;
2260       } else { // !in_pack(current, pk) ==> a sandwiched store
2261         remove_and_insert(current, previous, lower_insert_pt, upper_insert_pt, schedule_before_pack);
2262       }
2263 
2264       if (current == first) break;
2265       current = my_mem->as_Mem();
2266     } // end while
2267 
2268     // Reconnect loads back to upper_insert_pt.
2269     for (uint i = 0; i < memops.size(); i++) {
2270       Node *ld = memops.at(i);
2271       if (ld->in(MemNode::Memory) != upper_insert_pt) {
2272         _igvn.replace_input_of(ld, MemNode::Memory, upper_insert_pt);
2273       }
2274     }
2275   } else if (pk->at(0)->is_Load()) { // Load pack
2276     // All loads in the pack should have the same memory state. By default,
2277     // we use the memory state of the last load. However, if any load could
2278     // not be moved down due to the dependence constraint, we use the memory
2279     // state of the first load.
2280     Node* mem_input = pick_mem_state(pk);
2281     _igvn.hash_delete(mem_input);
2282     // Give each load the same memory state
2283     for (uint i = 0; i < pk->size(); i++) {
2284       LoadNode* ld = pk->at(i)->as_Load();
2285       _igvn.replace_input_of(ld, MemNode::Memory, mem_input);
2286     }
2287   }
2288 }
2289 
2290 // Finds the first and last memory state and then picks either of them by checking dependence constraints.
2291 // If a store is dependent on an earlier load then we need to pick the memory state of the first load and cannot
2292 // pick the memory state of the last load.
2293 Node* SuperWord::pick_mem_state(Node_List* pk) {
2294   Node* first_mem = find_first_mem_state(pk);
2295   Node* last_mem  = find_last_mem_state(pk, first_mem);
2296 
2297   for (uint i = 0; i < pk->size(); i++) {
2298     Node* ld = pk->at(i);
2299     for (Node* current = last_mem; current != ld->in(MemNode::Memory); current = current->in(MemNode::Memory)) {
2300       assert(current->is_Mem() && in_bb(current), "unexpected memory");
2301       assert(current != first_mem, "corrupted memory graph");
2302       if (!independent(current, ld)) {
2303 #ifdef ASSERT
2304         // Added assertion code since no case has been observed that should pick the first memory state.
2305         // Remove the assertion code whenever we find a (valid) case that really needs the first memory state.
2306         pk->dump();
2307         first_mem->dump();
2308         last_mem->dump();
2309         current->dump();
2310         ld->dump();
2311         ld->in(MemNode::Memory)->dump();
2312         assert(false, "never observed that first memory should be picked");
2313 #endif
2314         return first_mem; // A later store depends on this load, pick memory state of first load
2315       }
2316     }
2317   }
2318   return last_mem;
2319 }
2320 
2321 // Walk the memory graph from the current first load until the
2322 // start of the loop and check if nodes on the way are memory
2323 // edges of loads in the pack. The last one we encounter is the
2324 // first load.
2325 Node* SuperWord::find_first_mem_state(Node_List* pk) {
2326   Node* first_mem = pk->at(0)->in(MemNode::Memory);
2327   for (Node* current = first_mem; in_bb(current); current = current->is_Phi() ? current->in(LoopNode::EntryControl) : current->in(MemNode::Memory)) {
2328     assert(current->is_Mem() || (current->is_Phi() && current->in(0) == bb()), "unexpected memory");
2329     for (uint i = 1; i < pk->size(); i++) {
2330       Node* ld = pk->at(i);
2331       if (ld->in(MemNode::Memory) == current) {
2332         first_mem = current;
2333         break;
2334       }
2335     }
2336   }
2337   return first_mem;
2338 }
2339 
2340 // Find the last load by going over the pack again and walking
2341 // the memory graph from the loads of the pack to the memory of
2342 // the first load. If we encounter the memory of the current last
2343 // load, then we started from further down in the memory graph and
2344 // the load we started from is the last load.
2345 Node* SuperWord::find_last_mem_state(Node_List* pk, Node* first_mem) {
2346   Node* last_mem = pk->at(0)->in(MemNode::Memory);
2347   for (uint i = 0; i < pk->size(); i++) {
2348     Node* ld = pk->at(i);
2349     for (Node* current = ld->in(MemNode::Memory); current != first_mem; current = current->in(MemNode::Memory)) {
2350       assert(current->is_Mem() && in_bb(current), "unexpected memory");
2351       if (current->in(MemNode::Memory) == last_mem) {
2352         last_mem = ld->in(MemNode::Memory);
2353       }
2354     }
2355   }
2356   return last_mem;
2357 }
2358 
2359 #ifndef PRODUCT
2360 void SuperWord::print_loop(bool whole) {
2361   Node_Stack stack(_arena, _phase->C->unique() >> 2);
2362   Node_List rpo_list;
2363   VectorSet visited(_arena);
2364   visited.set(lpt()->_head->_idx);
2365   _phase->rpo(lpt()->_head, stack, visited, rpo_list);
2366   _phase->dump(lpt(), rpo_list.size(), rpo_list );
2367   if(whole) {
2368     tty->print_cr("\n Whole loop tree");
2369     _phase->dump();
2370     tty->print_cr(" End of whole loop tree\n");
2371   }
2372 }
2373 #endif
2374 
2375 //------------------------------output---------------------------
2376 // Convert packs into vector node operations
2377 void SuperWord::output() {
2378   CountedLoopNode *cl = lpt()->_head->as_CountedLoop();
2379   Compile* C = _phase->C;
2380   if (_packset.length() == 0) {
2381     if (cl->is_main_loop()) {
2382       // Instigate more unrolling for optimization when vectorization fails.
2383       C->set_major_progress();
2384       cl->set_notpassed_slp();
2385       cl->mark_do_unroll_only();
2386     }
2387     return;
2388   }
2389 
2390 #ifndef PRODUCT
2391   if (TraceLoopOpts) {
2392     tty->print("SuperWord::output    ");
2393     lpt()->dump_head();
2394   }
2395 #endif
2396 
2397   if (cl->is_main_loop()) {
2398     // MUST ENSURE main loop's initial value is properly aligned:
2399     //  (iv_initial_value + min_iv_offset) % vector_width_in_bytes() == 0
2400 
2401     align_initial_loop_index(align_to_ref());
2402 
2403     // Insert extract (unpack) operations for scalar uses
2404     for (int i = 0; i < _packset.length(); i++) {
2405       insert_extracts(_packset.at(i));
2406     }
2407   }
2408 
2409   uint max_vlen_in_bytes = 0;
2410   uint max_vlen = 0;
2411   bool can_process_post_loop = (PostLoopMultiversioning && Matcher::has_predicated_vectors() && cl->is_post_loop());
2412 
2413   NOT_PRODUCT(if(is_trace_loop_reverse()) {tty->print_cr("SWPointer::output: print loop before create_reserve_version_of_loop"); print_loop(true);})
2414 
2415   CountedLoopReserveKit make_reversable(_phase, _lpt, do_reserve_copy());
2416 
2417   NOT_PRODUCT(if(is_trace_loop_reverse()) {tty->print_cr("SWPointer::output: print loop after create_reserve_version_of_loop"); print_loop(true);})
2418 
2419   if (do_reserve_copy() && !make_reversable.has_reserved()) {
2420     NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: loop was not reserved correctly, exiting SuperWord");})
2421     return;
2422   }
2423 
2424   for (int i = 0; i < _block.length(); i++) {
2425     Node* n = _block.at(i);
2426     Node_List* p = my_pack(n);
2427     if (p && n == executed_last(p)) {
2428       uint vlen = p->size();
2429       uint vlen_in_bytes = 0;
2430       Node* vn = NULL;
2431       Node* low_adr = p->at(0);
2432       Node* first   = executed_first(p);
2433       if (can_process_post_loop) {
2434         // override vlen with the main loops vector length
2435         vlen = cl->slp_max_unroll();
2436       }
2437       NOT_PRODUCT(if(is_trace_cmov()) {tty->print_cr("SWPointer::output: %d executed first, %d executed last in pack", first->_idx, n->_idx); print_pack(p);})
2438       int   opc = n->Opcode();
2439       if (n->is_Load()) {
2440         Node* ctl = n->in(MemNode::Control);
2441         Node* mem = first->in(MemNode::Memory);
2442         SWPointer p1(n->as_Mem(), this, NULL, false);
2443         // Identify the memory dependency for the new loadVector node by
2444         // walking up through memory chain.
2445         // This is done to give flexibility to the new loadVector node so that
2446         // it can move above independent storeVector nodes.
2447         while (mem->is_StoreVector()) {
2448           SWPointer p2(mem->as_Mem(), this, NULL, false);
2449           int cmp = p1.cmp(p2);
2450           if (SWPointer::not_equal(cmp) || !SWPointer::comparable(cmp)) {
2451             mem = mem->in(MemNode::Memory);
2452           } else {
2453             break; // dependent memory
2454           }
2455         }
2456         Node* adr = low_adr->in(MemNode::Address);
2457         const TypePtr* atyp = n->adr_type();
2458         vn = LoadVectorNode::make(opc, ctl, mem, adr, atyp, vlen, velt_basic_type(n), control_dependency(p));
2459         vlen_in_bytes = vn->as_LoadVector()->memory_size();
2460       } else if (n->is_Store()) {
2461         // Promote value to be stored to vector
2462         Node* val = vector_opd(p, MemNode::ValueIn);
2463         if (val == NULL) {
2464           if (do_reserve_copy()) {
2465             NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: val should not be NULL, exiting SuperWord");})
2466             return; //and reverse to backup IG
2467           }
2468           ShouldNotReachHere();
2469         }
2470 
2471         Node* ctl = n->in(MemNode::Control);
2472         Node* mem = first->in(MemNode::Memory);
2473         Node* adr = low_adr->in(MemNode::Address);
2474         const TypePtr* atyp = n->adr_type();
2475         vn = StoreVectorNode::make(opc, ctl, mem, adr, atyp, val, vlen);
2476         vlen_in_bytes = vn->as_StoreVector()->memory_size();
2477       } else if (VectorNode::is_scalar_rotate(n)) {
2478         Node* in1 = low_adr->in(1);
2479         Node* in2 = p->at(0)->in(2);
2480         assert(in2->bottom_type()->isa_int(), "Shift must always be an int value");
2481         // If rotation count is non-constant or greater than 8bit value create a vector.
2482         if (!in2->is_Con() || -0x80 > in2->get_int() || in2->get_int() >= 0x80) {
2483           in2 =  vector_opd(p, 2);
2484         }
2485         vn = VectorNode::make(opc, in1, in2, vlen, velt_basic_type(n));
2486         vlen_in_bytes = vn->as_Vector()->length_in_bytes();
2487       } else if (VectorNode::is_roundopD(n)) {
2488         Node* in1 = vector_opd(p, 1);
2489         Node* in2 = low_adr->in(2);
2490         assert(in2->is_Con(), "Constant rounding mode expected.");
2491         vn = VectorNode::make(opc, in1, in2, vlen, velt_basic_type(n));
2492         vlen_in_bytes = vn->as_Vector()->length_in_bytes();
2493       } else if (VectorNode::is_muladds2i(n)) {
2494         assert(n->req() == 5u, "MulAddS2I should have 4 operands.");
2495         Node* in1 = vector_opd(p, 1);
2496         Node* in2 = vector_opd(p, 2);
2497         vn = VectorNode::make(opc, in1, in2, vlen, velt_basic_type(n));
2498         vlen_in_bytes = vn->as_Vector()->length_in_bytes();
2499       } else if (n->req() == 3 && !is_cmov_pack(p)) {
2500         // Promote operands to vector
2501         Node* in1 = NULL;
2502         bool node_isa_reduction = n->is_reduction();
2503         if (node_isa_reduction) {
2504           // the input to the first reduction operation is retained
2505           in1 = low_adr->in(1);
2506         } else {
2507           in1 = vector_opd(p, 1);
2508           if (in1 == NULL) {
2509             if (do_reserve_copy()) {
2510               NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: in1 should not be NULL, exiting SuperWord");})
2511               return; //and reverse to backup IG
2512             }
2513             ShouldNotReachHere();
2514           }
2515         }
2516         Node* in2 = vector_opd(p, 2);
2517         if (in2 == NULL) {
2518           if (do_reserve_copy()) {
2519             NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: in2 should not be NULL, exiting SuperWord");})
2520             return; //and reverse to backup IG
2521           }
2522           ShouldNotReachHere();
2523         }
2524         if (VectorNode::is_invariant_vector(in1) && (node_isa_reduction == false) && (n->is_Add() || n->is_Mul())) {
2525           // Move invariant vector input into second position to avoid register spilling.
2526           Node* tmp = in1;
2527           in1 = in2;
2528           in2 = tmp;
2529         }
2530         if (node_isa_reduction) {
2531           const Type *arith_type = n->bottom_type();
2532           vn = ReductionNode::make(opc, NULL, in1, in2, arith_type->basic_type());
2533           if (in2->is_Load()) {
2534             vlen_in_bytes = in2->as_LoadVector()->memory_size();
2535           } else {
2536             vlen_in_bytes = in2->as_Vector()->length_in_bytes();
2537           }
2538         } else {
2539           vn = VectorNode::make(opc, in1, in2, vlen, velt_basic_type(n));
2540           vlen_in_bytes = vn->as_Vector()->length_in_bytes();
2541         }
2542       } else if (opc == Op_SqrtF || opc == Op_SqrtD ||
2543                  opc == Op_AbsF || opc == Op_AbsD ||
2544                  opc == Op_AbsI || opc == Op_AbsL ||
2545                  opc == Op_NegF || opc == Op_NegD ||
2546                  opc == Op_PopCountI) {
2547         assert(n->req() == 2, "only one input expected");
2548         Node* in = vector_opd(p, 1);
2549         vn = VectorNode::make(opc, in, NULL, vlen, velt_basic_type(n));
2550         vlen_in_bytes = vn->as_Vector()->length_in_bytes();
2551       } else if (is_cmov_pack(p)) {
2552         if (can_process_post_loop) {
2553           // do not refactor of flow in post loop context
2554           return;
2555         }
2556         if (!n->is_CMove()) {
2557           continue;
2558         }
2559         // place here CMoveVDNode
2560         NOT_PRODUCT(if(is_trace_cmov()) {tty->print_cr("SWPointer::output: print before CMove vectorization"); print_loop(false);})
2561         Node* bol = n->in(CMoveNode::Condition);
2562         if (!bol->is_Bool() && bol->Opcode() == Op_ExtractI && bol->req() > 1 ) {
2563           NOT_PRODUCT(if(is_trace_cmov()) {tty->print_cr("SWPointer::output: %d is not Bool node, trying its in(1) node %d", bol->_idx, bol->in(1)->_idx); bol->dump(); bol->in(1)->dump();})
2564           bol = bol->in(1); //may be ExtractNode
2565         }
2566 
2567         assert(bol->is_Bool(), "should be BoolNode - too late to bail out!");
2568         if (!bol->is_Bool()) {
2569           if (do_reserve_copy()) {
2570             NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: expected %d bool node, exiting SuperWord", bol->_idx); bol->dump();})
2571             return; //and reverse to backup IG
2572           }
2573           ShouldNotReachHere();
2574         }
2575 
2576         int cond = (int)bol->as_Bool()->_test._test;
2577         Node* in_cc  = _igvn.intcon(cond);
2578         NOT_PRODUCT(if(is_trace_cmov()) {tty->print("SWPointer::output: created intcon in_cc node %d", in_cc->_idx); in_cc->dump();})
2579         Node* cc = bol->clone();
2580         cc->set_req(1, in_cc);
2581         NOT_PRODUCT(if(is_trace_cmov()) {tty->print("SWPointer::output: created bool cc node %d", cc->_idx); cc->dump();})
2582 
2583         Node* src1 = vector_opd(p, 2); //2=CMoveNode::IfFalse
2584         if (src1 == NULL) {
2585           if (do_reserve_copy()) {
2586             NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: src1 should not be NULL, exiting SuperWord");})
2587             return; //and reverse to backup IG
2588           }
2589           ShouldNotReachHere();
2590         }
2591         Node* src2 = vector_opd(p, 3); //3=CMoveNode::IfTrue
2592         if (src2 == NULL) {
2593           if (do_reserve_copy()) {
2594             NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: src2 should not be NULL, exiting SuperWord");})
2595             return; //and reverse to backup IG
2596           }
2597           ShouldNotReachHere();
2598         }
2599         BasicType bt = velt_basic_type(n);
2600         const TypeVect* vt = TypeVect::make(bt, vlen);
2601         assert(bt == T_FLOAT || bt == T_DOUBLE, "Only vectorization for FP cmovs is supported");
2602         if (bt == T_FLOAT) {
2603           vn = new CMoveVFNode(cc, src1, src2, vt);
2604         } else {
2605           assert(bt == T_DOUBLE, "Expected double");
2606           vn = new CMoveVDNode(cc, src1, src2, vt);
2607         }
2608         NOT_PRODUCT(if(is_trace_cmov()) {tty->print("SWPointer::output: created new CMove node %d: ", vn->_idx); vn->dump();})
2609       } else if (opc == Op_FmaD || opc == Op_FmaF) {
2610         // Promote operands to vector
2611         Node* in1 = vector_opd(p, 1);
2612         Node* in2 = vector_opd(p, 2);
2613         Node* in3 = vector_opd(p, 3);
2614         vn = VectorNode::make(opc, in1, in2, in3, vlen, velt_basic_type(n));
2615         vlen_in_bytes = vn->as_Vector()->length_in_bytes();
2616       } else {
2617         if (do_reserve_copy()) {
2618           NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: ShouldNotReachHere, exiting SuperWord");})
2619           return; //and reverse to backup IG
2620         }
2621         ShouldNotReachHere();
2622       }
2623 
2624       assert(vn != NULL, "sanity");
2625       if (vn == NULL) {
2626         if (do_reserve_copy()){
2627           NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: got NULL node, cannot proceed, exiting SuperWord");})
2628           return; //and reverse to backup IG
2629         }
2630         ShouldNotReachHere();
2631       }
2632 
2633       _block.at_put(i, vn);
2634       _igvn.register_new_node_with_optimizer(vn);
2635       _phase->set_ctrl(vn, _phase->get_ctrl(p->at(0)));
2636       for (uint j = 0; j < p->size(); j++) {
2637         Node* pm = p->at(j);
2638         _igvn.replace_node(pm, vn);
2639       }
2640       _igvn._worklist.push(vn);
2641 
2642       if (can_process_post_loop) {
2643         // first check if the vector size if the maximum vector which we can use on the machine,
2644         // other vector size have reduced values for predicated data mapping.
2645         if (vlen_in_bytes != (uint)MaxVectorSize) {
2646           return;
2647         }
2648       }
2649 
2650       if (vlen > max_vlen) {
2651         max_vlen = vlen;
2652       }
2653       if (vlen_in_bytes > max_vlen_in_bytes) {
2654         max_vlen_in_bytes = vlen_in_bytes;
2655       }
2656 #ifdef ASSERT
2657       if (TraceNewVectors) {
2658         tty->print("new Vector node: ");
2659         vn->dump();
2660       }
2661 #endif
2662     }
2663   }//for (int i = 0; i < _block.length(); i++)
2664 
2665   if (max_vlen_in_bytes > C->max_vector_size()) {
2666     C->set_max_vector_size(max_vlen_in_bytes);
2667   }
2668   if (max_vlen_in_bytes > 0) {
2669     cl->mark_loop_vectorized();
2670   }
2671 
2672   if (SuperWordLoopUnrollAnalysis) {
2673     if (cl->has_passed_slp()) {
2674       uint slp_max_unroll_factor = cl->slp_max_unroll();
2675       if (slp_max_unroll_factor == max_vlen) {
2676         if (TraceSuperWordLoopUnrollAnalysis) {
2677           tty->print_cr("vector loop(unroll=%d, len=%d)\n", max_vlen, max_vlen_in_bytes*BitsPerByte);
2678         }
2679 
2680         // For atomic unrolled loops which are vector mapped, instigate more unrolling
2681         cl->set_notpassed_slp();
2682         if (cl->is_main_loop()) {
2683           // if vector resources are limited, do not allow additional unrolling, also
2684           // do not unroll more on pure vector loops which were not reduced so that we can
2685           // program the post loop to single iteration execution.
2686           if (FLOATPRESSURE > 8) {
2687             C->set_major_progress();
2688             cl->mark_do_unroll_only();
2689           }
2690         }
2691 
2692         if (do_reserve_copy()) {
2693           if (can_process_post_loop) {
2694             // Now create the difference of trip and limit and use it as our mask index.
2695             // Note: We limited the unroll of the vectorized loop so that
2696             //       only vlen-1 size iterations can remain to be mask programmed.
2697             Node *incr = cl->incr();
2698             SubINode *index = new SubINode(cl->limit(), cl->init_trip());
2699             _igvn.register_new_node_with_optimizer(index);
2700             SetVectMaskINode  *mask = new SetVectMaskINode(_phase->get_ctrl(cl->init_trip()), index);
2701             _igvn.register_new_node_with_optimizer(mask);
2702             // make this a single iteration loop
2703             AddINode *new_incr = new AddINode(incr->in(1), mask);
2704             _igvn.register_new_node_with_optimizer(new_incr);
2705             _phase->set_ctrl(new_incr, _phase->get_ctrl(incr));
2706             _igvn.replace_node(incr, new_incr);
2707             cl->mark_is_multiversioned();
2708             cl->loopexit()->add_flag(Node::Flag_has_vector_mask_set);
2709           }
2710         }
2711       }
2712     }
2713   }
2714 
2715   if (do_reserve_copy()) {
2716     make_reversable.use_new();
2717   }
2718   NOT_PRODUCT(if(is_trace_loop_reverse()) {tty->print_cr("\n Final loop after SuperWord"); print_loop(true);})
2719   return;
2720 }
2721 
2722 //------------------------------vector_opd---------------------------
2723 // Create a vector operand for the nodes in pack p for operand: in(opd_idx)
2724 Node* SuperWord::vector_opd(Node_List* p, int opd_idx) {
2725   Node* p0 = p->at(0);
2726   uint vlen = p->size();
2727   Node* opd = p0->in(opd_idx);
2728   CountedLoopNode *cl = lpt()->_head->as_CountedLoop();
2729 
2730   if (PostLoopMultiversioning && Matcher::has_predicated_vectors() && cl->is_post_loop()) {
2731     // override vlen with the main loops vector length
2732     vlen = cl->slp_max_unroll();
2733   }
2734 
2735   if (same_inputs(p, opd_idx)) {
2736     if (opd->is_Vector() || opd->is_LoadVector()) {
2737       assert(((opd_idx != 2) || !VectorNode::is_shift(p0)), "shift's count can't be vector");
2738       if (opd_idx == 2 && VectorNode::is_shift(p0)) {
2739         NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("shift's count can't be vector");})
2740         return NULL;
2741       }
2742       return opd; // input is matching vector
2743     }
2744     if ((opd_idx == 2) && VectorNode::is_shift(p0)) {
2745       Compile* C = _phase->C;
2746       Node* cnt = opd;
2747       // Vector instructions do not mask shift count, do it here.
2748       juint mask = (p0->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1);
2749       const TypeInt* t = opd->find_int_type();
2750       if (t != NULL && t->is_con()) {
2751         juint shift = t->get_con();
2752         if (shift > mask) { // Unsigned cmp
2753           cnt = ConNode::make(TypeInt::make(shift & mask));
2754         }
2755       } else {
2756         if (t == NULL || t->_lo < 0 || t->_hi > (int)mask) {
2757           cnt = ConNode::make(TypeInt::make(mask));
2758           _igvn.register_new_node_with_optimizer(cnt);
2759           cnt = new AndINode(opd, cnt);
2760           _igvn.register_new_node_with_optimizer(cnt);
2761           _phase->set_ctrl(cnt, _phase->get_ctrl(opd));
2762         }
2763         assert(opd->bottom_type()->isa_int(), "int type only");
2764         if (!opd->bottom_type()->isa_int()) {
2765           NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("Should be int type only");})
2766           return NULL;
2767         }
2768       }
2769       // Move shift count into vector register.
2770       cnt = VectorNode::shift_count(p0, cnt, vlen, velt_basic_type(p0));
2771       _igvn.register_new_node_with_optimizer(cnt);
2772       _phase->set_ctrl(cnt, _phase->get_ctrl(opd));
2773       return cnt;
2774     }
2775     assert(!opd->is_StoreVector(), "such vector is not expected here");
2776     if (opd->is_StoreVector()) {
2777       NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("StoreVector is not expected here");})
2778       return NULL;
2779     }
2780     // Convert scalar input to vector with the same number of elements as
2781     // p0's vector. Use p0's type because size of operand's container in
2782     // vector should match p0's size regardless operand's size.
2783     const Type* p0_t = NULL;
2784     VectorNode* vn = NULL;
2785     if (opd_idx == 2 && VectorNode::is_scalar_rotate(p0)) {
2786        Node* conv = opd;
2787        p0_t =  TypeInt::INT;
2788        if (p0->bottom_type()->isa_long()) {
2789          p0_t = TypeLong::LONG;
2790          conv = new ConvI2LNode(opd);
2791          _igvn.register_new_node_with_optimizer(conv);
2792          _phase->set_ctrl(conv, _phase->get_ctrl(opd));
2793        }
2794        vn = VectorNode::scalar2vector(conv, vlen, p0_t);
2795     } else {
2796        p0_t =  velt_type(p0);
2797        vn = VectorNode::scalar2vector(opd, vlen, p0_t);
2798     }
2799 
2800     _igvn.register_new_node_with_optimizer(vn);
2801     _phase->set_ctrl(vn, _phase->get_ctrl(opd));
2802 #ifdef ASSERT
2803     if (TraceNewVectors) {
2804       tty->print("new Vector node: ");
2805       vn->dump();
2806     }
2807 #endif
2808     return vn;
2809   }
2810 
2811   // Insert pack operation
2812   BasicType bt = velt_basic_type(p0);
2813   PackNode* pk = PackNode::make(opd, vlen, bt);
2814   DEBUG_ONLY( const BasicType opd_bt = opd->bottom_type()->basic_type(); )
2815 
2816   for (uint i = 1; i < vlen; i++) {
2817     Node* pi = p->at(i);
2818     Node* in = pi->in(opd_idx);
2819     assert(my_pack(in) == NULL, "Should already have been unpacked");
2820     if (my_pack(in) != NULL) {
2821       NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("Should already have been unpacked");})
2822       return NULL;
2823     }
2824     assert(opd_bt == in->bottom_type()->basic_type(), "all same type");
2825     pk->add_opd(in);
2826     if (VectorNode::is_muladds2i(pi)) {
2827       Node* in2 = pi->in(opd_idx + 2);
2828       assert(my_pack(in2) == NULL, "Should already have been unpacked");
2829       if (my_pack(in2) != NULL) {
2830         NOT_PRODUCT(if (is_trace_loop_reverse() || TraceLoopOpts) { tty->print_cr("Should already have been unpacked"); })
2831           return NULL;
2832       }
2833       assert(opd_bt == in2->bottom_type()->basic_type(), "all same type");
2834       pk->add_opd(in2);
2835     }
2836   }
2837   _igvn.register_new_node_with_optimizer(pk);
2838   _phase->set_ctrl(pk, _phase->get_ctrl(opd));
2839 #ifdef ASSERT
2840   if (TraceNewVectors) {
2841     tty->print("new Vector node: ");
2842     pk->dump();
2843   }
2844 #endif
2845   return pk;
2846 }
2847 
2848 //------------------------------insert_extracts---------------------------
2849 // If a use of pack p is not a vector use, then replace the
2850 // use with an extract operation.
2851 void SuperWord::insert_extracts(Node_List* p) {
2852   if (p->at(0)->is_Store()) return;
2853   assert(_n_idx_list.is_empty(), "empty (node,index) list");
2854 
2855   // Inspect each use of each pack member.  For each use that is
2856   // not a vector use, replace the use with an extract operation.
2857 
2858   for (uint i = 0; i < p->size(); i++) {
2859     Node* def = p->at(i);
2860     for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
2861       Node* use = def->fast_out(j);
2862       for (uint k = 0; k < use->req(); k++) {
2863         Node* n = use->in(k);
2864         if (def == n) {
2865           Node_List* u_pk = my_pack(use);
2866           if ((u_pk == NULL || !is_cmov_pack(u_pk) || use->is_CMove()) && !is_vector_use(use, k)) {
2867               _n_idx_list.push(use, k);
2868           }
2869         }
2870       }
2871     }
2872   }
2873 
2874   while (_n_idx_list.is_nonempty()) {
2875     Node* use = _n_idx_list.node();
2876     int   idx = _n_idx_list.index();
2877     _n_idx_list.pop();
2878     Node* def = use->in(idx);
2879 
2880     if (def->is_reduction()) continue;
2881 
2882     // Insert extract operation
2883     _igvn.hash_delete(def);
2884     int def_pos = alignment(def) / data_size(def);
2885 
2886     Node* ex = ExtractNode::make(def, def_pos, velt_basic_type(def));
2887     _igvn.register_new_node_with_optimizer(ex);
2888     _phase->set_ctrl(ex, _phase->get_ctrl(def));
2889     _igvn.replace_input_of(use, idx, ex);
2890     _igvn._worklist.push(def);
2891 
2892     bb_insert_after(ex, bb_idx(def));
2893     set_velt_type(ex, velt_type(def));
2894   }
2895 }
2896 
2897 //------------------------------is_vector_use---------------------------
2898 // Is use->in(u_idx) a vector use?
2899 bool SuperWord::is_vector_use(Node* use, int u_idx) {
2900   Node_List* u_pk = my_pack(use);
2901   if (u_pk == NULL) return false;
2902   if (use->is_reduction()) return true;
2903   Node* def = use->in(u_idx);
2904   Node_List* d_pk = my_pack(def);
2905   if (d_pk == NULL) {
2906     // check for scalar promotion
2907     Node* n = u_pk->at(0)->in(u_idx);
2908     for (uint i = 1; i < u_pk->size(); i++) {
2909       if (u_pk->at(i)->in(u_idx) != n) return false;
2910     }
2911     return true;
2912   }
2913   if (VectorNode::is_muladds2i(use)) {
2914     // MulAddS2I takes shorts and produces ints - hence the special checks
2915     // on alignment and size.
2916     if (u_pk->size() * 2 != d_pk->size()) {
2917       return false;
2918     }
2919     for (uint i = 0; i < MIN2(d_pk->size(), u_pk->size()); i++) {
2920       Node* ui = u_pk->at(i);
2921       Node* di = d_pk->at(i);
2922       if (alignment(ui) != alignment(di) * 2) {
2923         return false;
2924       }
2925     }
2926     return true;
2927   }
2928   if (u_pk->size() != d_pk->size())
2929     return false;
2930   for (uint i = 0; i < u_pk->size(); i++) {
2931     Node* ui = u_pk->at(i);
2932     Node* di = d_pk->at(i);
2933     if (ui->in(u_idx) != di || alignment(ui) != alignment(di))
2934       return false;
2935   }
2936   return true;
2937 }
2938 
2939 //------------------------------construct_bb---------------------------
2940 // Construct reverse postorder list of block members
2941 bool SuperWord::construct_bb() {
2942   Node* entry = bb();
2943 
2944   assert(_stk.length() == 0,            "stk is empty");
2945   assert(_block.length() == 0,          "block is empty");
2946   assert(_data_entry.length() == 0,     "data_entry is empty");
2947   assert(_mem_slice_head.length() == 0, "mem_slice_head is empty");
2948   assert(_mem_slice_tail.length() == 0, "mem_slice_tail is empty");
2949 
2950   // Find non-control nodes with no inputs from within block,
2951   // create a temporary map from node _idx to bb_idx for use
2952   // by the visited and post_visited sets,
2953   // and count number of nodes in block.
2954   int bb_ct = 0;
2955   for (uint i = 0; i < lpt()->_body.size(); i++) {
2956     Node *n = lpt()->_body.at(i);
2957     set_bb_idx(n, i); // Create a temporary map
2958     if (in_bb(n)) {
2959       if (n->is_LoadStore() || n->is_MergeMem() ||
2960           (n->is_Proj() && !n->as_Proj()->is_CFG())) {
2961         // Bailout if the loop has LoadStore, MergeMem or data Proj
2962         // nodes. Superword optimization does not work with them.
2963         return false;
2964       }
2965       bb_ct++;
2966       if (!n->is_CFG()) {
2967         bool found = false;
2968         for (uint j = 0; j < n->req(); j++) {
2969           Node* def = n->in(j);
2970           if (def && in_bb(def)) {
2971             found = true;
2972             break;
2973           }
2974         }
2975         if (!found) {
2976           assert(n != entry, "can't be entry");
2977           _data_entry.push(n);
2978         }
2979       }
2980     }
2981   }
2982 
2983   // Find memory slices (head and tail)
2984   for (DUIterator_Fast imax, i = lp()->fast_outs(imax); i < imax; i++) {
2985     Node *n = lp()->fast_out(i);
2986     if (in_bb(n) && (n->is_Phi() && n->bottom_type() == Type::MEMORY)) {
2987       Node* n_tail  = n->in(LoopNode::LoopBackControl);
2988       if (n_tail != n->in(LoopNode::EntryControl)) {
2989         if (!n_tail->is_Mem()) {
2990           assert(n_tail->is_Mem(), "unexpected node for memory slice: %s", n_tail->Name());
2991           return false; // Bailout
2992         }
2993         _mem_slice_head.push(n);
2994         _mem_slice_tail.push(n_tail);
2995       }
2996     }
2997   }
2998 
2999   // Create an RPO list of nodes in block
3000 
3001   visited_clear();
3002   post_visited_clear();
3003 
3004   // Push all non-control nodes with no inputs from within block, then control entry
3005   for (int j = 0; j < _data_entry.length(); j++) {
3006     Node* n = _data_entry.at(j);
3007     visited_set(n);
3008     _stk.push(n);
3009   }
3010   visited_set(entry);
3011   _stk.push(entry);
3012 
3013   // Do a depth first walk over out edges
3014   int rpo_idx = bb_ct - 1;
3015   int size;
3016   int reduction_uses = 0;
3017   while ((size = _stk.length()) > 0) {
3018     Node* n = _stk.top(); // Leave node on stack
3019     if (!visited_test_set(n)) {
3020       // forward arc in graph
3021     } else if (!post_visited_test(n)) {
3022       // cross or back arc
3023       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3024         Node *use = n->fast_out(i);
3025         if (in_bb(use) && !visited_test(use) &&
3026             // Don't go around backedge
3027             (!use->is_Phi() || n == entry)) {
3028           if (use->is_reduction()) {
3029             // First see if we can map the reduction on the given system we are on, then
3030             // make a data entry operation for each reduction we see.
3031             BasicType bt = use->bottom_type()->basic_type();
3032             if (ReductionNode::implemented(use->Opcode(), Matcher::min_vector_size(bt), bt)) {
3033               reduction_uses++;
3034             }
3035           }
3036           _stk.push(use);
3037         }
3038       }
3039       if (_stk.length() == size) {
3040         // There were no additional uses, post visit node now
3041         _stk.pop(); // Remove node from stack
3042         assert(rpo_idx >= 0, "");
3043         _block.at_put_grow(rpo_idx, n);
3044         rpo_idx--;
3045         post_visited_set(n);
3046         assert(rpo_idx >= 0 || _stk.is_empty(), "");
3047       }
3048     } else {
3049       _stk.pop(); // Remove post-visited node from stack
3050     }
3051   }//while
3052 
3053   int ii_current = -1;
3054   unsigned int load_idx = (unsigned int)-1;
3055   _ii_order.clear();
3056   // Create real map of block indices for nodes
3057   for (int j = 0; j < _block.length(); j++) {
3058     Node* n = _block.at(j);
3059     set_bb_idx(n, j);
3060     if (_do_vector_loop && n->is_Load()) {
3061       if (ii_current == -1) {
3062         ii_current = _clone_map.gen(n->_idx);
3063         _ii_order.push(ii_current);
3064         load_idx = _clone_map.idx(n->_idx);
3065       } else if (_clone_map.idx(n->_idx) == load_idx && _clone_map.gen(n->_idx) != ii_current) {
3066         ii_current = _clone_map.gen(n->_idx);
3067         _ii_order.push(ii_current);
3068       }
3069     }
3070   }//for
3071 
3072   // Ensure extra info is allocated.
3073   initialize_bb();
3074 
3075 #ifndef PRODUCT
3076   if (_vector_loop_debug && _ii_order.length() > 0) {
3077     tty->print("SuperWord::construct_bb: List of generations: ");
3078     for (int jj = 0; jj < _ii_order.length(); ++jj) {
3079       tty->print("  %d:%d", jj, _ii_order.at(jj));
3080     }
3081     tty->print_cr(" ");
3082   }
3083   if (TraceSuperWord) {
3084     print_bb();
3085     tty->print_cr("\ndata entry nodes: %s", _data_entry.length() > 0 ? "" : "NONE");
3086     for (int m = 0; m < _data_entry.length(); m++) {
3087       tty->print("%3d ", m);
3088       _data_entry.at(m)->dump();
3089     }
3090     tty->print_cr("\nmemory slices: %s", _mem_slice_head.length() > 0 ? "" : "NONE");
3091     for (int m = 0; m < _mem_slice_head.length(); m++) {
3092       tty->print("%3d ", m); _mem_slice_head.at(m)->dump();
3093       tty->print("    ");    _mem_slice_tail.at(m)->dump();
3094     }
3095   }
3096 #endif
3097   assert(rpo_idx == -1 && bb_ct == _block.length(), "all block members found");
3098   return (_mem_slice_head.length() > 0) || (reduction_uses > 0) || (_data_entry.length() > 0);
3099 }
3100 
3101 //------------------------------initialize_bb---------------------------
3102 // Initialize per node info
3103 void SuperWord::initialize_bb() {
3104   Node* last = _block.at(_block.length() - 1);
3105   grow_node_info(bb_idx(last));
3106 }
3107 
3108 //------------------------------bb_insert_after---------------------------
3109 // Insert n into block after pos
3110 void SuperWord::bb_insert_after(Node* n, int pos) {
3111   int n_pos = pos + 1;
3112   // Make room
3113   for (int i = _block.length() - 1; i >= n_pos; i--) {
3114     _block.at_put_grow(i+1, _block.at(i));
3115   }
3116   for (int j = _node_info.length() - 1; j >= n_pos; j--) {
3117     _node_info.at_put_grow(j+1, _node_info.at(j));
3118   }
3119   // Set value
3120   _block.at_put_grow(n_pos, n);
3121   _node_info.at_put_grow(n_pos, SWNodeInfo::initial);
3122   // Adjust map from node->_idx to _block index
3123   for (int i = n_pos; i < _block.length(); i++) {
3124     set_bb_idx(_block.at(i), i);
3125   }
3126 }
3127 
3128 //------------------------------compute_max_depth---------------------------
3129 // Compute max depth for expressions from beginning of block
3130 // Use to prune search paths during test for independence.
3131 void SuperWord::compute_max_depth() {
3132   int ct = 0;
3133   bool again;
3134   do {
3135     again = false;
3136     for (int i = 0; i < _block.length(); i++) {
3137       Node* n = _block.at(i);
3138       if (!n->is_Phi()) {
3139         int d_orig = depth(n);
3140         int d_in   = 0;
3141         for (DepPreds preds(n, _dg); !preds.done(); preds.next()) {
3142           Node* pred = preds.current();
3143           if (in_bb(pred)) {
3144             d_in = MAX2(d_in, depth(pred));
3145           }
3146         }
3147         if (d_in + 1 != d_orig) {
3148           set_depth(n, d_in + 1);
3149           again = true;
3150         }
3151       }
3152     }
3153     ct++;
3154   } while (again);
3155 
3156   if (TraceSuperWord && Verbose) {
3157     tty->print_cr("compute_max_depth iterated: %d times", ct);
3158   }
3159 }
3160 
3161 //-------------------------compute_vector_element_type-----------------------
3162 // Compute necessary vector element type for expressions
3163 // This propagates backwards a narrower integer type when the
3164 // upper bits of the value are not needed.
3165 // Example:  char a,b,c;  a = b + c;
3166 // Normally the type of the add is integer, but for packed character
3167 // operations the type of the add needs to be char.
3168 void SuperWord::compute_vector_element_type() {
3169   if (TraceSuperWord && Verbose) {
3170     tty->print_cr("\ncompute_velt_type:");
3171   }
3172 
3173   // Initial type
3174   for (int i = 0; i < _block.length(); i++) {
3175     Node* n = _block.at(i);
3176     set_velt_type(n, container_type(n));
3177   }
3178 
3179   // Propagate integer narrowed type backwards through operations
3180   // that don't depend on higher order bits
3181   for (int i = _block.length() - 1; i >= 0; i--) {
3182     Node* n = _block.at(i);
3183     // Only integer types need be examined
3184     const Type* vtn = velt_type(n);
3185     if (vtn->basic_type() == T_INT) {
3186       uint start, end;
3187       VectorNode::vector_operands(n, &start, &end);
3188 
3189       for (uint j = start; j < end; j++) {
3190         Node* in  = n->in(j);
3191         // Don't propagate through a memory
3192         if (!in->is_Mem() && in_bb(in) && velt_type(in)->basic_type() == T_INT &&
3193             data_size(n) < data_size(in)) {
3194           bool same_type = true;
3195           for (DUIterator_Fast kmax, k = in->fast_outs(kmax); k < kmax; k++) {
3196             Node *use = in->fast_out(k);
3197             if (!in_bb(use) || !same_velt_type(use, n)) {
3198               same_type = false;
3199               break;
3200             }
3201           }
3202           if (same_type) {
3203             // For right shifts of small integer types (bool, byte, char, short)
3204             // we need precise information about sign-ness. Only Load nodes have
3205             // this information because Store nodes are the same for signed and
3206             // unsigned values. And any arithmetic operation after a load may
3207             // expand a value to signed Int so such right shifts can't be used
3208             // because vector elements do not have upper bits of Int.
3209             const Type* vt = vtn;
3210             if (VectorNode::is_shift(in)) {
3211               Node* load = in->in(1);
3212               if (load->is_Load() && in_bb(load) && (velt_type(load)->basic_type() == T_INT)) {
3213                 vt = velt_type(load);
3214               } else if (in->Opcode() != Op_LShiftI) {
3215                 // Widen type to Int to avoid creation of right shift vector
3216                 // (align + data_size(s1) check in stmts_can_pack() will fail).
3217                 // Note, left shifts work regardless type.
3218                 vt = TypeInt::INT;
3219               }
3220             }
3221             set_velt_type(in, vt);
3222           }
3223         }
3224       }
3225     }
3226   }
3227 #ifndef PRODUCT
3228   if (TraceSuperWord && Verbose) {
3229     for (int i = 0; i < _block.length(); i++) {
3230       Node* n = _block.at(i);
3231       velt_type(n)->dump();
3232       tty->print("\t");
3233       n->dump();
3234     }
3235   }
3236 #endif
3237 }
3238 
3239 //------------------------------memory_alignment---------------------------
3240 // Alignment within a vector memory reference
3241 int SuperWord::memory_alignment(MemNode* s, int iv_adjust) {
3242 #ifndef PRODUCT
3243   if ((TraceSuperWord && Verbose) || is_trace_alignment()) {
3244     tty->print("SuperWord::memory_alignment within a vector memory reference for %d:  ", s->_idx); s->dump();
3245   }
3246 #endif
3247   NOT_PRODUCT(SWPointer::Tracer::Depth ddd(0);)
3248   SWPointer p(s, this, NULL, false);
3249   if (!p.valid()) {
3250     NOT_PRODUCT(if(is_trace_alignment()) tty->print_cr("SWPointer::memory_alignment: SWPointer p invalid, return bottom_align");)
3251     return bottom_align;
3252   }
3253   int vw = get_vw_bytes_special(s);
3254   if (vw < 2) {
3255     NOT_PRODUCT(if(is_trace_alignment()) tty->print_cr("SWPointer::memory_alignment: vector_width_in_bytes < 2, return bottom_align");)
3256     return bottom_align; // No vectors for this type
3257   }
3258   int offset  = p.offset_in_bytes();
3259   offset     += iv_adjust*p.memory_size();
3260   int off_rem = offset % vw;
3261   int off_mod = off_rem >= 0 ? off_rem : off_rem + vw;
3262 #ifndef PRODUCT
3263   if ((TraceSuperWord && Verbose) || is_trace_alignment()) {
3264     tty->print_cr("SWPointer::memory_alignment: off_rem = %d, off_mod = %d", off_rem, off_mod);
3265   }
3266 #endif
3267   return off_mod;
3268 }
3269 
3270 //---------------------------container_type---------------------------
3271 // Smallest type containing range of values
3272 const Type* SuperWord::container_type(Node* n) {
3273   if (n->is_Mem()) {
3274     BasicType bt = n->as_Mem()->memory_type();
3275     if (n->is_Store() && (bt == T_CHAR)) {
3276       // Use T_SHORT type instead of T_CHAR for stored values because any
3277       // preceding arithmetic operation extends values to signed Int.
3278       bt = T_SHORT;
3279     }
3280     if (n->Opcode() == Op_LoadUB) {
3281       // Adjust type for unsigned byte loads, it is important for right shifts.
3282       // T_BOOLEAN is used because there is no basic type representing type
3283       // TypeInt::UBYTE. Use of T_BOOLEAN for vectors is fine because only
3284       // size (one byte) and sign is important.
3285       bt = T_BOOLEAN;
3286     }
3287     return Type::get_const_basic_type(bt);
3288   }
3289   const Type* t = _igvn.type(n);
3290   if (t->basic_type() == T_INT) {
3291     // A narrow type of arithmetic operations will be determined by
3292     // propagating the type of memory operations.
3293     return TypeInt::INT;
3294   }
3295   return t;
3296 }
3297 
3298 bool SuperWord::same_velt_type(Node* n1, Node* n2) {
3299   const Type* vt1 = velt_type(n1);
3300   const Type* vt2 = velt_type(n2);
3301   if (vt1->basic_type() == T_INT && vt2->basic_type() == T_INT) {
3302     // Compare vectors element sizes for integer types.
3303     return data_size(n1) == data_size(n2);
3304   }
3305   return vt1 == vt2;
3306 }
3307 
3308 //------------------------------in_packset---------------------------
3309 // Are s1 and s2 in a pack pair and ordered as s1,s2?
3310 bool SuperWord::in_packset(Node* s1, Node* s2) {
3311   for (int i = 0; i < _packset.length(); i++) {
3312     Node_List* p = _packset.at(i);
3313     assert(p->size() == 2, "must be");
3314     if (p->at(0) == s1 && p->at(p->size()-1) == s2) {
3315       return true;
3316     }
3317   }
3318   return false;
3319 }
3320 
3321 //------------------------------in_pack---------------------------
3322 // Is s in pack p?
3323 Node_List* SuperWord::in_pack(Node* s, Node_List* p) {
3324   for (uint i = 0; i < p->size(); i++) {
3325     if (p->at(i) == s) {
3326       return p;
3327     }
3328   }
3329   return NULL;
3330 }
3331 
3332 //------------------------------remove_pack_at---------------------------
3333 // Remove the pack at position pos in the packset
3334 void SuperWord::remove_pack_at(int pos) {
3335   Node_List* p = _packset.at(pos);
3336   for (uint i = 0; i < p->size(); i++) {
3337     Node* s = p->at(i);
3338     set_my_pack(s, NULL);
3339   }
3340   _packset.remove_at(pos);
3341 }
3342 
3343 void SuperWord::packset_sort(int n) {
3344   // simple bubble sort so that we capitalize with O(n) when its already sorted
3345   while (n != 0) {
3346     bool swapped = false;
3347     for (int i = 1; i < n; i++) {
3348       Node_List* q_low = _packset.at(i-1);
3349       Node_List* q_i = _packset.at(i);
3350 
3351       // only swap when we find something to swap
3352       if (alignment(q_low->at(0)) > alignment(q_i->at(0))) {
3353         Node_List* t = q_i;
3354         *(_packset.adr_at(i)) = q_low;
3355         *(_packset.adr_at(i-1)) = q_i;
3356         swapped = true;
3357       }
3358     }
3359     if (swapped == false) break;
3360     n--;
3361   }
3362 }
3363 
3364 //------------------------------executed_first---------------------------
3365 // Return the node executed first in pack p.  Uses the RPO block list
3366 // to determine order.
3367 Node* SuperWord::executed_first(Node_List* p) {
3368   Node* n = p->at(0);
3369   int n_rpo = bb_idx(n);
3370   for (uint i = 1; i < p->size(); i++) {
3371     Node* s = p->at(i);
3372     int s_rpo = bb_idx(s);
3373     if (s_rpo < n_rpo) {
3374       n = s;
3375       n_rpo = s_rpo;
3376     }
3377   }
3378   return n;
3379 }
3380 
3381 //------------------------------executed_last---------------------------
3382 // Return the node executed last in pack p.
3383 Node* SuperWord::executed_last(Node_List* p) {
3384   Node* n = p->at(0);
3385   int n_rpo = bb_idx(n);
3386   for (uint i = 1; i < p->size(); i++) {
3387     Node* s = p->at(i);
3388     int s_rpo = bb_idx(s);
3389     if (s_rpo > n_rpo) {
3390       n = s;
3391       n_rpo = s_rpo;
3392     }
3393   }
3394   return n;
3395 }
3396 
3397 LoadNode::ControlDependency SuperWord::control_dependency(Node_List* p) {
3398   LoadNode::ControlDependency dep = LoadNode::DependsOnlyOnTest;
3399   for (uint i = 0; i < p->size(); i++) {
3400     Node* n = p->at(i);
3401     assert(n->is_Load(), "only meaningful for loads");
3402     if (!n->depends_only_on_test()) {
3403       if (n->as_Load()->has_unknown_control_dependency() &&
3404           dep != LoadNode::Pinned) {
3405         // Upgrade to unknown control...
3406         dep = LoadNode::UnknownControl;
3407       } else {
3408         // Otherwise, we must pin it.
3409         dep = LoadNode::Pinned;
3410       }
3411     }
3412   }
3413   return dep;
3414 }
3415 
3416 
3417 //----------------------------align_initial_loop_index---------------------------
3418 // Adjust pre-loop limit so that in main loop, a load/store reference
3419 // to align_to_ref will be a position zero in the vector.
3420 //   (iv + k) mod vector_align == 0
3421 void SuperWord::align_initial_loop_index(MemNode* align_to_ref) {
3422   CountedLoopNode *main_head = lp()->as_CountedLoop();
3423   assert(main_head->is_main_loop(), "");
3424   CountedLoopEndNode* pre_end = get_pre_loop_end(main_head);
3425   assert(pre_end != NULL, "we must have a correct pre-loop");
3426   Node *pre_opaq1 = pre_end->limit();
3427   assert(pre_opaq1->Opcode() == Op_Opaque1, "");
3428   Opaque1Node *pre_opaq = (Opaque1Node*)pre_opaq1;
3429   Node *lim0 = pre_opaq->in(1);
3430 
3431   // Where we put new limit calculations
3432   Node *pre_ctrl = pre_end->loopnode()->in(LoopNode::EntryControl);
3433 
3434   // Ensure the original loop limit is available from the
3435   // pre-loop Opaque1 node.
3436   Node *orig_limit = pre_opaq->original_loop_limit();
3437   assert(orig_limit != NULL && _igvn.type(orig_limit) != Type::TOP, "");
3438 
3439   SWPointer align_to_ref_p(align_to_ref, this, NULL, false);
3440   assert(align_to_ref_p.valid(), "sanity");
3441 
3442   // Given:
3443   //     lim0 == original pre loop limit
3444   //     V == v_align (power of 2)
3445   //     invar == extra invariant piece of the address expression
3446   //     e == offset [ +/- invar ]
3447   //
3448   // When reassociating expressions involving '%' the basic rules are:
3449   //     (a - b) % k == 0   =>  a % k == b % k
3450   // and:
3451   //     (a + b) % k == 0   =>  a % k == (k - b) % k
3452   //
3453   // For stride > 0 && scale > 0,
3454   //   Derive the new pre-loop limit "lim" such that the two constraints:
3455   //     (1) lim = lim0 + N           (where N is some positive integer < V)
3456   //     (2) (e + lim) % V == 0
3457   //   are true.
3458   //
3459   //   Substituting (1) into (2),
3460   //     (e + lim0 + N) % V == 0
3461   //   solve for N:
3462   //     N = (V - (e + lim0)) % V
3463   //   substitute back into (1), so that new limit
3464   //     lim = lim0 + (V - (e + lim0)) % V
3465   //
3466   // For stride > 0 && scale < 0
3467   //   Constraints:
3468   //     lim = lim0 + N
3469   //     (e - lim) % V == 0
3470   //   Solving for lim:
3471   //     (e - lim0 - N) % V == 0
3472   //     N = (e - lim0) % V
3473   //     lim = lim0 + (e - lim0) % V
3474   //
3475   // For stride < 0 && scale > 0
3476   //   Constraints:
3477   //     lim = lim0 - N
3478   //     (e + lim) % V == 0
3479   //   Solving for lim:
3480   //     (e + lim0 - N) % V == 0
3481   //     N = (e + lim0) % V
3482   //     lim = lim0 - (e + lim0) % V
3483   //
3484   // For stride < 0 && scale < 0
3485   //   Constraints:
3486   //     lim = lim0 - N
3487   //     (e - lim) % V == 0
3488   //   Solving for lim:
3489   //     (e - lim0 + N) % V == 0
3490   //     N = (V - (e - lim0)) % V
3491   //     lim = lim0 - (V - (e - lim0)) % V
3492 
3493   int vw = vector_width_in_bytes(align_to_ref);
3494   int stride   = iv_stride();
3495   int scale    = align_to_ref_p.scale_in_bytes();
3496   int elt_size = align_to_ref_p.memory_size();
3497   int v_align  = vw / elt_size;
3498   assert(v_align > 1, "sanity");
3499   int offset   = align_to_ref_p.offset_in_bytes() / elt_size;
3500   Node *offsn  = _igvn.intcon(offset);
3501 
3502   Node *e = offsn;
3503   if (align_to_ref_p.invar() != NULL) {
3504     // incorporate any extra invariant piece producing (offset +/- invar) >>> log2(elt)
3505     Node* log2_elt = _igvn.intcon(exact_log2(elt_size));
3506     Node* invar = align_to_ref_p.invar();
3507     if (_igvn.type(invar)->isa_long()) {
3508       // Computations are done % (vector width/element size) so it's
3509       // safe to simply convert invar to an int and loose the upper 32
3510       // bit half.
3511       invar = new ConvL2INode(invar);
3512       _igvn.register_new_node_with_optimizer(invar);
3513     }
3514     Node* aref = new URShiftINode(invar, log2_elt);
3515     _igvn.register_new_node_with_optimizer(aref);
3516     _phase->set_ctrl(aref, pre_ctrl);
3517     if (align_to_ref_p.negate_invar()) {
3518       e = new SubINode(e, aref);
3519     } else {
3520       e = new AddINode(e, aref);
3521     }
3522     _igvn.register_new_node_with_optimizer(e);
3523     _phase->set_ctrl(e, pre_ctrl);
3524   }
3525   if (vw > ObjectAlignmentInBytes || align_to_ref_p.base()->is_top()) {
3526     // incorporate base e +/- base && Mask >>> log2(elt)
3527     Node* xbase = new CastP2XNode(NULL, align_to_ref_p.adr());
3528     _igvn.register_new_node_with_optimizer(xbase);
3529 #ifdef _LP64
3530     xbase  = new ConvL2INode(xbase);
3531     _igvn.register_new_node_with_optimizer(xbase);
3532 #endif
3533     Node* mask = _igvn.intcon(vw-1);
3534     Node* masked_xbase  = new AndINode(xbase, mask);
3535     _igvn.register_new_node_with_optimizer(masked_xbase);
3536     Node* log2_elt = _igvn.intcon(exact_log2(elt_size));
3537     Node* bref     = new URShiftINode(masked_xbase, log2_elt);
3538     _igvn.register_new_node_with_optimizer(bref);
3539     _phase->set_ctrl(bref, pre_ctrl);
3540     e = new AddINode(e, bref);
3541     _igvn.register_new_node_with_optimizer(e);
3542     _phase->set_ctrl(e, pre_ctrl);
3543   }
3544 
3545   // compute e +/- lim0
3546   if (scale < 0) {
3547     e = new SubINode(e, lim0);
3548   } else {
3549     e = new AddINode(e, lim0);
3550   }
3551   _igvn.register_new_node_with_optimizer(e);
3552   _phase->set_ctrl(e, pre_ctrl);
3553 
3554   if (stride * scale > 0) {
3555     // compute V - (e +/- lim0)
3556     Node* va  = _igvn.intcon(v_align);
3557     e = new SubINode(va, e);
3558     _igvn.register_new_node_with_optimizer(e);
3559     _phase->set_ctrl(e, pre_ctrl);
3560   }
3561   // compute N = (exp) % V
3562   Node* va_msk = _igvn.intcon(v_align - 1);
3563   Node* N = new AndINode(e, va_msk);
3564   _igvn.register_new_node_with_optimizer(N);
3565   _phase->set_ctrl(N, pre_ctrl);
3566 
3567   //   substitute back into (1), so that new limit
3568   //     lim = lim0 + N
3569   Node* lim;
3570   if (stride < 0) {
3571     lim = new SubINode(lim0, N);
3572   } else {
3573     lim = new AddINode(lim0, N);
3574   }
3575   _igvn.register_new_node_with_optimizer(lim);
3576   _phase->set_ctrl(lim, pre_ctrl);
3577   Node* constrained =
3578     (stride > 0) ? (Node*) new MinINode(lim, orig_limit)
3579                  : (Node*) new MaxINode(lim, orig_limit);
3580   _igvn.register_new_node_with_optimizer(constrained);
3581   _phase->set_ctrl(constrained, pre_ctrl);
3582   _igvn.replace_input_of(pre_opaq, 1, constrained);
3583 }
3584 
3585 //----------------------------get_pre_loop_end---------------------------
3586 // Find pre loop end from main loop.  Returns null if none.
3587 CountedLoopEndNode* SuperWord::get_pre_loop_end(CountedLoopNode* cl) {
3588   // The loop cannot be optimized if the graph shape at
3589   // the loop entry is inappropriate.
3590   if (!PhaseIdealLoop::is_canonical_loop_entry(cl)) {
3591     return NULL;
3592   }
3593 
3594   Node* p_f = cl->skip_predicates()->in(0)->in(0);
3595   if (!p_f->is_IfFalse()) return NULL;
3596   if (!p_f->in(0)->is_CountedLoopEnd()) return NULL;
3597   CountedLoopEndNode* pre_end = p_f->in(0)->as_CountedLoopEnd();
3598   CountedLoopNode* loop_node = pre_end->loopnode();
3599   if (loop_node == NULL || !loop_node->is_pre_loop()) return NULL;
3600   return pre_end;
3601 }
3602 
3603 //------------------------------init---------------------------
3604 void SuperWord::init() {
3605   _dg.init();
3606   _packset.clear();
3607   _disjoint_ptrs.clear();
3608   _block.clear();
3609   _post_block.clear();
3610   _data_entry.clear();
3611   _mem_slice_head.clear();
3612   _mem_slice_tail.clear();
3613   _iteration_first.clear();
3614   _iteration_last.clear();
3615   _node_info.clear();
3616   _align_to_ref = NULL;
3617   _lpt = NULL;
3618   _lp = NULL;
3619   _bb = NULL;
3620   _iv = NULL;
3621   _race_possible = 0;
3622   _early_return = false;
3623   _num_work_vecs = 0;
3624   _num_reductions = 0;
3625 }
3626 
3627 //------------------------------restart---------------------------
3628 void SuperWord::restart() {
3629   _dg.init();
3630   _packset.clear();
3631   _disjoint_ptrs.clear();
3632   _block.clear();
3633   _post_block.clear();
3634   _data_entry.clear();
3635   _mem_slice_head.clear();
3636   _mem_slice_tail.clear();
3637   _node_info.clear();
3638 }
3639 
3640 //------------------------------print_packset---------------------------
3641 void SuperWord::print_packset() {
3642 #ifndef PRODUCT
3643   tty->print_cr("packset");
3644   for (int i = 0; i < _packset.length(); i++) {
3645     tty->print_cr("Pack: %d", i);
3646     Node_List* p = _packset.at(i);
3647     print_pack(p);
3648   }
3649 #endif
3650 }
3651 
3652 //------------------------------print_pack---------------------------
3653 void SuperWord::print_pack(Node_List* p) {
3654   for (uint i = 0; i < p->size(); i++) {
3655     print_stmt(p->at(i));
3656   }
3657 }
3658 
3659 //------------------------------print_bb---------------------------
3660 void SuperWord::print_bb() {
3661 #ifndef PRODUCT
3662   tty->print_cr("\nBlock");
3663   for (int i = 0; i < _block.length(); i++) {
3664     Node* n = _block.at(i);
3665     tty->print("%d ", i);
3666     if (n) {
3667       n->dump();
3668     }
3669   }
3670 #endif
3671 }
3672 
3673 //------------------------------print_stmt---------------------------
3674 void SuperWord::print_stmt(Node* s) {
3675 #ifndef PRODUCT
3676   tty->print(" align: %d \t", alignment(s));
3677   s->dump();
3678 #endif
3679 }
3680 
3681 //------------------------------blank---------------------------
3682 char* SuperWord::blank(uint depth) {
3683   static char blanks[101];
3684   assert(depth < 101, "too deep");
3685   for (uint i = 0; i < depth; i++) blanks[i] = ' ';
3686   blanks[depth] = '\0';
3687   return blanks;
3688 }
3689 
3690 
3691 //==============================SWPointer===========================
3692 #ifndef PRODUCT
3693 int SWPointer::Tracer::_depth = 0;
3694 #endif
3695 //----------------------------SWPointer------------------------
3696 SWPointer::SWPointer(MemNode* mem, SuperWord* slp, Node_Stack *nstack, bool analyze_only) :
3697   _mem(mem), _slp(slp),  _base(NULL),  _adr(NULL),
3698   _scale(0), _offset(0), _invar(NULL), _negate_invar(false),
3699   _nstack(nstack), _analyze_only(analyze_only),
3700   _stack_idx(0)
3701 #ifndef PRODUCT
3702   , _tracer(slp)
3703 #endif
3704 {
3705   NOT_PRODUCT(_tracer.ctor_1(mem);)
3706 
3707   Node* adr = mem->in(MemNode::Address);
3708   if (!adr->is_AddP()) {
3709     assert(!valid(), "too complex");
3710     return;
3711   }
3712   // Match AddP(base, AddP(ptr, k*iv [+ invariant]), constant)
3713   Node* base = adr->in(AddPNode::Base);
3714   // The base address should be loop invariant
3715   if (!invariant(base)) {
3716     assert(!valid(), "base address is loop variant");
3717     return;
3718   }
3719   // unsafe references require misaligned vector access support
3720   if (base->is_top() && !Matcher::misaligned_vectors_ok()) {
3721     assert(!valid(), "unsafe access");
3722     return;
3723   }
3724 
3725   NOT_PRODUCT(if(_slp->is_trace_alignment()) _tracer.store_depth();)
3726   NOT_PRODUCT(_tracer.ctor_2(adr);)
3727 
3728   int i;
3729   for (i = 0; i < 3; i++) {
3730     NOT_PRODUCT(_tracer.ctor_3(adr, i);)
3731 
3732     if (!scaled_iv_plus_offset(adr->in(AddPNode::Offset))) {
3733       assert(!valid(), "too complex");
3734       return;
3735     }
3736     adr = adr->in(AddPNode::Address);
3737     NOT_PRODUCT(_tracer.ctor_4(adr, i);)
3738 
3739     if (base == adr || !adr->is_AddP()) {
3740       NOT_PRODUCT(_tracer.ctor_5(adr, base, i);)
3741       break; // stop looking at addp's
3742     }
3743   }
3744   if (!invariant(adr)) {
3745     assert(!valid(), "adr is loop variant");
3746     return;
3747   }
3748 
3749   if (!base->is_top() && adr != base) {
3750     assert(!valid(), "adr and base differ");
3751     return;
3752   }
3753 
3754   NOT_PRODUCT(if(_slp->is_trace_alignment()) _tracer.restore_depth();)
3755   NOT_PRODUCT(_tracer.ctor_6(mem);)
3756 
3757   _base = base;
3758   _adr  = adr;
3759   assert(valid(), "Usable");
3760 }
3761 
3762 // Following is used to create a temporary object during
3763 // the pattern match of an address expression.
3764 SWPointer::SWPointer(SWPointer* p) :
3765   _mem(p->_mem), _slp(p->_slp),  _base(NULL),  _adr(NULL),
3766   _scale(0), _offset(0), _invar(NULL), _negate_invar(false),
3767   _nstack(p->_nstack), _analyze_only(p->_analyze_only),
3768   _stack_idx(p->_stack_idx)
3769   #ifndef PRODUCT
3770   , _tracer(p->_slp)
3771   #endif
3772 {}
3773 
3774 
3775 bool SWPointer::invariant(Node* n) {
3776   NOT_PRODUCT(Tracer::Depth dd;)
3777   Node *n_c = phase()->get_ctrl(n);
3778   NOT_PRODUCT(_tracer.invariant_1(n, n_c);)
3779   return !lpt()->is_member(phase()->get_loop(n_c));
3780 }
3781 
3782 //------------------------scaled_iv_plus_offset--------------------
3783 // Match: k*iv + offset
3784 // where: k is a constant that maybe zero, and
3785 //        offset is (k2 [+/- invariant]) where k2 maybe zero and invariant is optional
3786 bool SWPointer::scaled_iv_plus_offset(Node* n) {
3787   NOT_PRODUCT(Tracer::Depth ddd;)
3788   NOT_PRODUCT(_tracer.scaled_iv_plus_offset_1(n);)
3789 
3790   if (scaled_iv(n)) {
3791     NOT_PRODUCT(_tracer.scaled_iv_plus_offset_2(n);)
3792     return true;
3793   }
3794 
3795   if (offset_plus_k(n)) {
3796     NOT_PRODUCT(_tracer.scaled_iv_plus_offset_3(n);)
3797     return true;
3798   }
3799 
3800   int opc = n->Opcode();
3801   if (opc == Op_AddI) {
3802     if (offset_plus_k(n->in(2)) && scaled_iv_plus_offset(n->in(1))) {
3803       NOT_PRODUCT(_tracer.scaled_iv_plus_offset_4(n);)
3804       return true;
3805     }
3806     if (offset_plus_k(n->in(1)) && scaled_iv_plus_offset(n->in(2))) {
3807       NOT_PRODUCT(_tracer.scaled_iv_plus_offset_5(n);)
3808       return true;
3809     }
3810   } else if (opc == Op_SubI) {
3811     if (offset_plus_k(n->in(2), true) && scaled_iv_plus_offset(n->in(1))) {
3812       NOT_PRODUCT(_tracer.scaled_iv_plus_offset_6(n);)
3813       return true;
3814     }
3815     if (offset_plus_k(n->in(1)) && scaled_iv_plus_offset(n->in(2))) {
3816       _scale *= -1;
3817       NOT_PRODUCT(_tracer.scaled_iv_plus_offset_7(n);)
3818       return true;
3819     }
3820   }
3821 
3822   NOT_PRODUCT(_tracer.scaled_iv_plus_offset_8(n);)
3823   return false;
3824 }
3825 
3826 //----------------------------scaled_iv------------------------
3827 // Match: k*iv where k is a constant that's not zero
3828 bool SWPointer::scaled_iv(Node* n) {
3829   NOT_PRODUCT(Tracer::Depth ddd;)
3830   NOT_PRODUCT(_tracer.scaled_iv_1(n);)
3831 
3832   if (_scale != 0) { // already found a scale
3833     NOT_PRODUCT(_tracer.scaled_iv_2(n, _scale);)
3834     return false;
3835   }
3836 
3837   if (n == iv()) {
3838     _scale = 1;
3839     NOT_PRODUCT(_tracer.scaled_iv_3(n, _scale);)
3840     return true;
3841   }
3842   if (_analyze_only && (invariant(n) == false)) {
3843     _nstack->push(n, _stack_idx++);
3844   }
3845 
3846   int opc = n->Opcode();
3847   if (opc == Op_MulI) {
3848     if (n->in(1) == iv() && n->in(2)->is_Con()) {
3849       _scale = n->in(2)->get_int();
3850       NOT_PRODUCT(_tracer.scaled_iv_4(n, _scale);)
3851       return true;
3852     } else if (n->in(2) == iv() && n->in(1)->is_Con()) {
3853       _scale = n->in(1)->get_int();
3854       NOT_PRODUCT(_tracer.scaled_iv_5(n, _scale);)
3855       return true;
3856     }
3857   } else if (opc == Op_LShiftI) {
3858     if (n->in(1) == iv() && n->in(2)->is_Con()) {
3859       _scale = 1 << n->in(2)->get_int();
3860       NOT_PRODUCT(_tracer.scaled_iv_6(n, _scale);)
3861       return true;
3862     }
3863   } else if (opc == Op_ConvI2L) {
3864     if (n->in(1)->Opcode() == Op_CastII &&
3865         n->in(1)->as_CastII()->has_range_check()) {
3866       // Skip range check dependent CastII nodes
3867       n = n->in(1);
3868     }
3869     if (scaled_iv_plus_offset(n->in(1))) {
3870       NOT_PRODUCT(_tracer.scaled_iv_7(n);)
3871       return true;
3872     }
3873   } else if (opc == Op_LShiftL) {
3874     if (!has_iv() && _invar == NULL) {
3875       // Need to preserve the current _offset value, so
3876       // create a temporary object for this expression subtree.
3877       // Hacky, so should re-engineer the address pattern match.
3878       NOT_PRODUCT(Tracer::Depth dddd;)
3879       SWPointer tmp(this);
3880       NOT_PRODUCT(_tracer.scaled_iv_8(n, &tmp);)
3881 
3882       if (tmp.scaled_iv_plus_offset(n->in(1))) {
3883         if (tmp._invar == NULL || _slp->do_vector_loop()) {
3884           int mult = 1 << n->in(2)->get_int();
3885           _scale   = tmp._scale  * mult;
3886           _offset += tmp._offset * mult;
3887           _invar = tmp._invar;
3888           NOT_PRODUCT(_tracer.scaled_iv_9(n, _scale, _offset, mult);)
3889           return true;
3890         }
3891       }
3892     }
3893   }
3894   NOT_PRODUCT(_tracer.scaled_iv_10(n);)
3895   return false;
3896 }
3897 
3898 //----------------------------offset_plus_k------------------------
3899 // Match: offset is (k [+/- invariant])
3900 // where k maybe zero and invariant is optional, but not both.
3901 bool SWPointer::offset_plus_k(Node* n, bool negate) {
3902   NOT_PRODUCT(Tracer::Depth ddd;)
3903   NOT_PRODUCT(_tracer.offset_plus_k_1(n);)
3904 
3905   int opc = n->Opcode();
3906   if (opc == Op_ConI) {
3907     _offset += negate ? -(n->get_int()) : n->get_int();
3908     NOT_PRODUCT(_tracer.offset_plus_k_2(n, _offset);)
3909     return true;
3910   } else if (opc == Op_ConL) {
3911     // Okay if value fits into an int
3912     const TypeLong* t = n->find_long_type();
3913     if (t->higher_equal(TypeLong::INT)) {
3914       jlong loff = n->get_long();
3915       jint  off  = (jint)loff;
3916       _offset += negate ? -off : loff;
3917       NOT_PRODUCT(_tracer.offset_plus_k_3(n, _offset);)
3918       return true;
3919     }
3920     NOT_PRODUCT(_tracer.offset_plus_k_4(n);)
3921     return false;
3922   }
3923   if (_invar != NULL) { // already has an invariant
3924     NOT_PRODUCT(_tracer.offset_plus_k_5(n, _invar);)
3925     return false;
3926   }
3927 
3928   if (_analyze_only && (invariant(n) == false)) {
3929     _nstack->push(n, _stack_idx++);
3930   }
3931   if (opc == Op_AddI) {
3932     if (n->in(2)->is_Con() && invariant(n->in(1))) {
3933       _negate_invar = negate;
3934       _invar = n->in(1);
3935       _offset += negate ? -(n->in(2)->get_int()) : n->in(2)->get_int();
3936       NOT_PRODUCT(_tracer.offset_plus_k_6(n, _invar, _negate_invar, _offset);)
3937       return true;
3938     } else if (n->in(1)->is_Con() && invariant(n->in(2))) {
3939       _offset += negate ? -(n->in(1)->get_int()) : n->in(1)->get_int();
3940       _negate_invar = negate;
3941       _invar = n->in(2);
3942       NOT_PRODUCT(_tracer.offset_plus_k_7(n, _invar, _negate_invar, _offset);)
3943       return true;
3944     }
3945   }
3946   if (opc == Op_SubI) {
3947     if (n->in(2)->is_Con() && invariant(n->in(1))) {
3948       _negate_invar = negate;
3949       _invar = n->in(1);
3950       _offset += !negate ? -(n->in(2)->get_int()) : n->in(2)->get_int();
3951       NOT_PRODUCT(_tracer.offset_plus_k_8(n, _invar, _negate_invar, _offset);)
3952       return true;
3953     } else if (n->in(1)->is_Con() && invariant(n->in(2))) {
3954       _offset += negate ? -(n->in(1)->get_int()) : n->in(1)->get_int();
3955       _negate_invar = !negate;
3956       _invar = n->in(2);
3957       NOT_PRODUCT(_tracer.offset_plus_k_9(n, _invar, _negate_invar, _offset);)
3958       return true;
3959     }
3960   }
3961   if (invariant(n)) {
3962     if (opc == Op_ConvI2L) {
3963       n = n->in(1);
3964       if (n->Opcode() == Op_CastII &&
3965           n->as_CastII()->has_range_check()) {
3966         // Skip range check dependent CastII nodes
3967         assert(invariant(n), "sanity");
3968         n = n->in(1);
3969       }
3970     }
3971     _negate_invar = negate;
3972     _invar = n;
3973     NOT_PRODUCT(_tracer.offset_plus_k_10(n, _invar, _negate_invar, _offset);)
3974     return true;
3975   }
3976 
3977   NOT_PRODUCT(_tracer.offset_plus_k_11(n);)
3978   return false;
3979 }
3980 
3981 //----------------------------print------------------------
3982 void SWPointer::print() {
3983 #ifndef PRODUCT
3984   tty->print("base: %d  adr: %d  scale: %d  offset: %d  invar: %c%d\n",
3985              _base != NULL ? _base->_idx : 0,
3986              _adr  != NULL ? _adr->_idx  : 0,
3987              _scale, _offset,
3988              _negate_invar?'-':'+',
3989              _invar != NULL ? _invar->_idx : 0);
3990 #endif
3991 }
3992 
3993 //----------------------------tracing------------------------
3994 #ifndef PRODUCT
3995 void SWPointer::Tracer::print_depth() {
3996   for (int ii = 0; ii<_depth; ++ii) tty->print("  ");
3997 }
3998 
3999 void SWPointer::Tracer::ctor_1 (Node* mem) {
4000   if(_slp->is_trace_alignment()) {
4001     print_depth(); tty->print(" %d SWPointer::SWPointer: start alignment analysis", mem->_idx); mem->dump();
4002   }
4003 }
4004 
4005 void SWPointer::Tracer::ctor_2(Node* adr) {
4006   if(_slp->is_trace_alignment()) {
4007     //store_depth();
4008     inc_depth();
4009     print_depth(); tty->print(" %d (adr) SWPointer::SWPointer: ", adr->_idx); adr->dump();
4010     inc_depth();
4011     print_depth(); tty->print(" %d (base) SWPointer::SWPointer: ", adr->in(AddPNode::Base)->_idx); adr->in(AddPNode::Base)->dump();
4012   }
4013 }
4014 
4015 void SWPointer::Tracer::ctor_3(Node* adr, int i) {
4016   if(_slp->is_trace_alignment()) {
4017     inc_depth();
4018     Node* offset = adr->in(AddPNode::Offset);
4019     print_depth(); tty->print(" %d (offset) SWPointer::SWPointer: i = %d: ", offset->_idx, i); offset->dump();
4020   }
4021 }
4022 
4023 void SWPointer::Tracer::ctor_4(Node* adr, int i) {
4024   if(_slp->is_trace_alignment()) {
4025     inc_depth();
4026     print_depth(); tty->print(" %d (adr) SWPointer::SWPointer: i = %d: ", adr->_idx, i); adr->dump();
4027   }
4028 }
4029 
4030 void SWPointer::Tracer::ctor_5(Node* adr, Node* base, int i) {
4031   if(_slp->is_trace_alignment()) {
4032     inc_depth();
4033     if (base == adr) {
4034       print_depth(); tty->print_cr("  \\ %d (adr) == %d (base) SWPointer::SWPointer: breaking analysis at i = %d", adr->_idx, base->_idx, i);
4035     } else if (!adr->is_AddP()) {
4036       print_depth(); tty->print_cr("  \\ %d (adr) is NOT Addp SWPointer::SWPointer: breaking analysis at i = %d", adr->_idx, i);
4037     }
4038   }
4039 }
4040 
4041 void SWPointer::Tracer::ctor_6(Node* mem) {
4042   if(_slp->is_trace_alignment()) {
4043     //restore_depth();
4044     print_depth(); tty->print_cr(" %d (adr) SWPointer::SWPointer: stop analysis", mem->_idx);
4045   }
4046 }
4047 
4048 void SWPointer::Tracer::invariant_1(Node *n, Node *n_c) {
4049   if (_slp->do_vector_loop() && _slp->is_debug() && _slp->_lpt->is_member(_slp->_phase->get_loop(n_c)) != (int)_slp->in_bb(n)) {
4050     int is_member =  _slp->_lpt->is_member(_slp->_phase->get_loop(n_c));
4051     int in_bb     =  _slp->in_bb(n);
4052     print_depth(); tty->print("  \\ ");  tty->print_cr(" %d SWPointer::invariant  conditions differ: n_c %d", n->_idx, n_c->_idx);
4053     print_depth(); tty->print("  \\ ");  tty->print_cr("is_member %d, in_bb %d", is_member, in_bb);
4054     print_depth(); tty->print("  \\ ");  n->dump();
4055     print_depth(); tty->print("  \\ ");  n_c->dump();
4056   }
4057 }
4058 
4059 void SWPointer::Tracer::scaled_iv_plus_offset_1(Node* n) {
4060   if(_slp->is_trace_alignment()) {
4061     print_depth(); tty->print(" %d SWPointer::scaled_iv_plus_offset testing node: ", n->_idx);
4062     n->dump();
4063   }
4064 }
4065 
4066 void SWPointer::Tracer::scaled_iv_plus_offset_2(Node* n) {
4067   if(_slp->is_trace_alignment()) {
4068     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: PASSED", n->_idx);
4069   }
4070 }
4071 
4072 void SWPointer::Tracer::scaled_iv_plus_offset_3(Node* n) {
4073   if(_slp->is_trace_alignment()) {
4074     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: PASSED", n->_idx);
4075   }
4076 }
4077 
4078 void SWPointer::Tracer::scaled_iv_plus_offset_4(Node* n) {
4079   if(_slp->is_trace_alignment()) {
4080     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: Op_AddI PASSED", n->_idx);
4081     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(1) is scaled_iv: ", n->in(1)->_idx); n->in(1)->dump();
4082     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(2) is offset_plus_k: ", n->in(2)->_idx); n->in(2)->dump();
4083   }
4084 }
4085 
4086 void SWPointer::Tracer::scaled_iv_plus_offset_5(Node* n) {
4087   if(_slp->is_trace_alignment()) {
4088     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: Op_AddI PASSED", n->_idx);
4089     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(2) is scaled_iv: ", n->in(2)->_idx); n->in(2)->dump();
4090     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(1) is offset_plus_k: ", n->in(1)->_idx); n->in(1)->dump();
4091   }
4092 }
4093 
4094 void SWPointer::Tracer::scaled_iv_plus_offset_6(Node* n) {
4095   if(_slp->is_trace_alignment()) {
4096     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: Op_SubI PASSED", n->_idx);
4097     print_depth(); tty->print("  \\  %d SWPointer::scaled_iv_plus_offset: in(1) is scaled_iv: ", n->in(1)->_idx); n->in(1)->dump();
4098     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(2) is offset_plus_k: ", n->in(2)->_idx); n->in(2)->dump();
4099   }
4100 }
4101 
4102 void SWPointer::Tracer::scaled_iv_plus_offset_7(Node* n) {
4103   if(_slp->is_trace_alignment()) {
4104     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: Op_SubI PASSED", n->_idx);
4105     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(2) is scaled_iv: ", n->in(2)->_idx); n->in(2)->dump();
4106     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(1) is offset_plus_k: ", n->in(1)->_idx); n->in(1)->dump();
4107   }
4108 }
4109 
4110 void SWPointer::Tracer::scaled_iv_plus_offset_8(Node* n) {
4111   if(_slp->is_trace_alignment()) {
4112     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: FAILED", n->_idx);
4113   }
4114 }
4115 
4116 void SWPointer::Tracer::scaled_iv_1(Node* n) {
4117   if(_slp->is_trace_alignment()) {
4118     print_depth(); tty->print(" %d SWPointer::scaled_iv: testing node: ", n->_idx); n->dump();
4119   }
4120 }
4121 
4122 void SWPointer::Tracer::scaled_iv_2(Node* n, int scale) {
4123   if(_slp->is_trace_alignment()) {
4124     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: FAILED since another _scale has been detected before", n->_idx);
4125     print_depth(); tty->print_cr("  \\ SWPointer::scaled_iv: _scale (%d) != 0", scale);
4126   }
4127 }
4128 
4129 void SWPointer::Tracer::scaled_iv_3(Node* n, int scale) {
4130   if(_slp->is_trace_alignment()) {
4131     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: is iv, setting _scale = %d", n->_idx, scale);
4132   }
4133 }
4134 
4135 void SWPointer::Tracer::scaled_iv_4(Node* n, int scale) {
4136   if(_slp->is_trace_alignment()) {
4137     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: Op_MulI PASSED, setting _scale = %d", n->_idx, scale);
4138     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(1) is iv: ", n->in(1)->_idx); n->in(1)->dump();
4139     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(2) is Con: ", n->in(2)->_idx); n->in(2)->dump();
4140   }
4141 }
4142 
4143 void SWPointer::Tracer::scaled_iv_5(Node* n, int scale) {
4144   if(_slp->is_trace_alignment()) {
4145     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: Op_MulI PASSED, setting _scale = %d", n->_idx, scale);
4146     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(2) is iv: ", n->in(2)->_idx); n->in(2)->dump();
4147     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(1) is Con: ", n->in(1)->_idx); n->in(1)->dump();
4148   }
4149 }
4150 
4151 void SWPointer::Tracer::scaled_iv_6(Node* n, int scale) {
4152   if(_slp->is_trace_alignment()) {
4153     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: Op_LShiftI PASSED, setting _scale = %d", n->_idx, scale);
4154     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(1) is iv: ", n->in(1)->_idx); n->in(1)->dump();
4155     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(2) is Con: ", n->in(2)->_idx); n->in(2)->dump();
4156   }
4157 }
4158 
4159 void SWPointer::Tracer::scaled_iv_7(Node* n) {
4160   if(_slp->is_trace_alignment()) {
4161     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: Op_ConvI2L PASSED", n->_idx);
4162     print_depth(); tty->print_cr("  \\ SWPointer::scaled_iv: in(1) %d is scaled_iv_plus_offset: ", n->in(1)->_idx);
4163     inc_depth(); inc_depth();
4164     print_depth(); n->in(1)->dump();
4165     dec_depth(); dec_depth();
4166   }
4167 }
4168 
4169 void SWPointer::Tracer::scaled_iv_8(Node* n, SWPointer* tmp) {
4170   if(_slp->is_trace_alignment()) {
4171     print_depth(); tty->print(" %d SWPointer::scaled_iv: Op_LShiftL, creating tmp SWPointer: ", n->_idx); tmp->print();
4172   }
4173 }
4174 
4175 void SWPointer::Tracer::scaled_iv_9(Node* n, int scale, int _offset, int mult) {
4176   if(_slp->is_trace_alignment()) {
4177     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: Op_LShiftL PASSED, setting _scale = %d, _offset = %d", n->_idx, scale, _offset);
4178     print_depth(); tty->print_cr("  \\ SWPointer::scaled_iv: in(1) %d is scaled_iv_plus_offset, in(2) %d used to get mult = %d: _scale = %d, _offset = %d",
4179     n->in(1)->_idx, n->in(2)->_idx, mult, scale, _offset);
4180     inc_depth(); inc_depth();
4181     print_depth(); n->in(1)->dump();
4182     print_depth(); n->in(2)->dump();
4183     dec_depth(); dec_depth();
4184   }
4185 }
4186 
4187 void SWPointer::Tracer::scaled_iv_10(Node* n) {
4188   if(_slp->is_trace_alignment()) {
4189     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: FAILED", n->_idx);
4190   }
4191 }
4192 
4193 void SWPointer::Tracer::offset_plus_k_1(Node* n) {
4194   if(_slp->is_trace_alignment()) {
4195     print_depth(); tty->print(" %d SWPointer::offset_plus_k: testing node: ", n->_idx); n->dump();
4196   }
4197 }
4198 
4199 void SWPointer::Tracer::offset_plus_k_2(Node* n, int _offset) {
4200   if(_slp->is_trace_alignment()) {
4201     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_ConI PASSED, setting _offset = %d", n->_idx, _offset);
4202   }
4203 }
4204 
4205 void SWPointer::Tracer::offset_plus_k_3(Node* n, int _offset) {
4206   if(_slp->is_trace_alignment()) {
4207     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_ConL PASSED, setting _offset = %d", n->_idx, _offset);
4208   }
4209 }
4210 
4211 void SWPointer::Tracer::offset_plus_k_4(Node* n) {
4212   if(_slp->is_trace_alignment()) {
4213     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: FAILED", n->_idx);
4214     print_depth(); tty->print_cr("  \\ " JLONG_FORMAT " SWPointer::offset_plus_k: Op_ConL FAILED, k is too big", n->get_long());
4215   }
4216 }
4217 
4218 void SWPointer::Tracer::offset_plus_k_5(Node* n, Node* _invar) {
4219   if(_slp->is_trace_alignment()) {
4220     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: FAILED since another invariant has been detected before", n->_idx);
4221     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: _invar != NULL: ", _invar->_idx); _invar->dump();
4222   }
4223 }
4224 
4225 void SWPointer::Tracer::offset_plus_k_6(Node* n, Node* _invar, bool _negate_invar, int _offset) {
4226   if(_slp->is_trace_alignment()) {
4227     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_AddI PASSED, setting _negate_invar = %d, _invar = %d, _offset = %d",
4228     n->_idx, _negate_invar, _invar->_idx, _offset);
4229     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(2) is Con: ", n->in(2)->_idx); n->in(2)->dump();
4230     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(1) is invariant: ", _invar->_idx); _invar->dump();
4231   }
4232 }
4233 
4234 void SWPointer::Tracer::offset_plus_k_7(Node* n, Node* _invar, bool _negate_invar, int _offset) {
4235   if(_slp->is_trace_alignment()) {
4236     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_AddI PASSED, setting _negate_invar = %d, _invar = %d, _offset = %d",
4237     n->_idx, _negate_invar, _invar->_idx, _offset);
4238     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(1) is Con: ", n->in(1)->_idx); n->in(1)->dump();
4239     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(2) is invariant: ", _invar->_idx); _invar->dump();
4240   }
4241 }
4242 
4243 void SWPointer::Tracer::offset_plus_k_8(Node* n, Node* _invar, bool _negate_invar, int _offset) {
4244   if(_slp->is_trace_alignment()) {
4245     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_SubI is PASSED, setting _negate_invar = %d, _invar = %d, _offset = %d",
4246     n->_idx, _negate_invar, _invar->_idx, _offset);
4247     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(2) is Con: ", n->in(2)->_idx); n->in(2)->dump();
4248     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(1) is invariant: ", _invar->_idx); _invar->dump();
4249   }
4250 }
4251 
4252 void SWPointer::Tracer::offset_plus_k_9(Node* n, Node* _invar, bool _negate_invar, int _offset) {
4253   if(_slp->is_trace_alignment()) {
4254     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_SubI PASSED, setting _negate_invar = %d, _invar = %d, _offset = %d", n->_idx, _negate_invar, _invar->_idx, _offset);
4255     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(1) is Con: ", n->in(1)->_idx); n->in(1)->dump();
4256     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(2) is invariant: ", _invar->_idx); _invar->dump();
4257   }
4258 }
4259 
4260 void SWPointer::Tracer::offset_plus_k_10(Node* n, Node* _invar, bool _negate_invar, int _offset) {
4261   if(_slp->is_trace_alignment()) {
4262     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: PASSED, setting _negate_invar = %d, _invar = %d, _offset = %d", n->_idx, _negate_invar, _invar->_idx, _offset);
4263     print_depth(); tty->print_cr("  \\ %d SWPointer::offset_plus_k: is invariant", n->_idx);
4264   }
4265 }
4266 
4267 void SWPointer::Tracer::offset_plus_k_11(Node* n) {
4268   if(_slp->is_trace_alignment()) {
4269     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: FAILED", n->_idx);
4270   }
4271 }
4272 
4273 #endif
4274 // ========================= OrderedPair =====================
4275 
4276 const OrderedPair OrderedPair::initial;
4277 
4278 // ========================= SWNodeInfo =====================
4279 
4280 const SWNodeInfo SWNodeInfo::initial;
4281 
4282 
4283 // ============================ DepGraph ===========================
4284 
4285 //------------------------------make_node---------------------------
4286 // Make a new dependence graph node for an ideal node.
4287 DepMem* DepGraph::make_node(Node* node) {
4288   DepMem* m = new (_arena) DepMem(node);
4289   if (node != NULL) {
4290     assert(_map.at_grow(node->_idx) == NULL, "one init only");
4291     _map.at_put_grow(node->_idx, m);
4292   }
4293   return m;
4294 }
4295 
4296 //------------------------------make_edge---------------------------
4297 // Make a new dependence graph edge from dpred -> dsucc
4298 DepEdge* DepGraph::make_edge(DepMem* dpred, DepMem* dsucc) {
4299   DepEdge* e = new (_arena) DepEdge(dpred, dsucc, dsucc->in_head(), dpred->out_head());
4300   dpred->set_out_head(e);
4301   dsucc->set_in_head(e);
4302   return e;
4303 }
4304 
4305 // ========================== DepMem ========================
4306 
4307 //------------------------------in_cnt---------------------------
4308 int DepMem::in_cnt() {
4309   int ct = 0;
4310   for (DepEdge* e = _in_head; e != NULL; e = e->next_in()) ct++;
4311   return ct;
4312 }
4313 
4314 //------------------------------out_cnt---------------------------
4315 int DepMem::out_cnt() {
4316   int ct = 0;
4317   for (DepEdge* e = _out_head; e != NULL; e = e->next_out()) ct++;
4318   return ct;
4319 }
4320 
4321 //------------------------------print-----------------------------
4322 void DepMem::print() {
4323 #ifndef PRODUCT
4324   tty->print("  DepNode %d (", _node->_idx);
4325   for (DepEdge* p = _in_head; p != NULL; p = p->next_in()) {
4326     Node* pred = p->pred()->node();
4327     tty->print(" %d", pred != NULL ? pred->_idx : 0);
4328   }
4329   tty->print(") [");
4330   for (DepEdge* s = _out_head; s != NULL; s = s->next_out()) {
4331     Node* succ = s->succ()->node();
4332     tty->print(" %d", succ != NULL ? succ->_idx : 0);
4333   }
4334   tty->print_cr(" ]");
4335 #endif
4336 }
4337 
4338 // =========================== DepEdge =========================
4339 
4340 //------------------------------DepPreds---------------------------
4341 void DepEdge::print() {
4342 #ifndef PRODUCT
4343   tty->print_cr("DepEdge: %d [ %d ]", _pred->node()->_idx, _succ->node()->_idx);
4344 #endif
4345 }
4346 
4347 // =========================== DepPreds =========================
4348 // Iterator over predecessor edges in the dependence graph.
4349 
4350 //------------------------------DepPreds---------------------------
4351 DepPreds::DepPreds(Node* n, DepGraph& dg) {
4352   _n = n;
4353   _done = false;
4354   if (_n->is_Store() || _n->is_Load()) {
4355     _next_idx = MemNode::Address;
4356     _end_idx  = n->req();
4357     _dep_next = dg.dep(_n)->in_head();
4358   } else if (_n->is_Mem()) {
4359     _next_idx = 0;
4360     _end_idx  = 0;
4361     _dep_next = dg.dep(_n)->in_head();
4362   } else {
4363     _next_idx = 1;
4364     _end_idx  = _n->req();
4365     _dep_next = NULL;
4366   }
4367   next();
4368 }
4369 
4370 //------------------------------next---------------------------
4371 void DepPreds::next() {
4372   if (_dep_next != NULL) {
4373     _current  = _dep_next->pred()->node();
4374     _dep_next = _dep_next->next_in();
4375   } else if (_next_idx < _end_idx) {
4376     _current  = _n->in(_next_idx++);
4377   } else {
4378     _done = true;
4379   }
4380 }
4381 
4382 // =========================== DepSuccs =========================
4383 // Iterator over successor edges in the dependence graph.
4384 
4385 //------------------------------DepSuccs---------------------------
4386 DepSuccs::DepSuccs(Node* n, DepGraph& dg) {
4387   _n = n;
4388   _done = false;
4389   if (_n->is_Load()) {
4390     _next_idx = 0;
4391     _end_idx  = _n->outcnt();
4392     _dep_next = dg.dep(_n)->out_head();
4393   } else if (_n->is_Mem() || (_n->is_Phi() && _n->bottom_type() == Type::MEMORY)) {
4394     _next_idx = 0;
4395     _end_idx  = 0;
4396     _dep_next = dg.dep(_n)->out_head();
4397   } else {
4398     _next_idx = 0;
4399     _end_idx  = _n->outcnt();
4400     _dep_next = NULL;
4401   }
4402   next();
4403 }
4404 
4405 //-------------------------------next---------------------------
4406 void DepSuccs::next() {
4407   if (_dep_next != NULL) {
4408     _current  = _dep_next->succ()->node();
4409     _dep_next = _dep_next->next_out();
4410   } else if (_next_idx < _end_idx) {
4411     _current  = _n->raw_out(_next_idx++);
4412   } else {
4413     _done = true;
4414   }
4415 }
4416 
4417 //
4418 // --------------------------------- vectorization/simd -----------------------------------
4419 //
4420 bool SuperWord::same_origin_idx(Node* a, Node* b) const {
4421   return a != NULL && b != NULL && _clone_map.same_idx(a->_idx, b->_idx);
4422 }
4423 bool SuperWord::same_generation(Node* a, Node* b) const {
4424   return a != NULL && b != NULL && _clone_map.same_gen(a->_idx, b->_idx);
4425 }
4426 
4427 Node*  SuperWord::find_phi_for_mem_dep(LoadNode* ld) {
4428   assert(in_bb(ld), "must be in block");
4429   if (_clone_map.gen(ld->_idx) == _ii_first) {
4430 #ifndef PRODUCT
4431     if (_vector_loop_debug) {
4432       tty->print_cr("SuperWord::find_phi_for_mem_dep _clone_map.gen(ld->_idx)=%d",
4433         _clone_map.gen(ld->_idx));
4434     }
4435 #endif
4436     return NULL; //we think that any ld in the first gen being vectorizable
4437   }
4438 
4439   Node* mem = ld->in(MemNode::Memory);
4440   if (mem->outcnt() <= 1) {
4441     // we don't want to remove the only edge from mem node to load
4442 #ifndef PRODUCT
4443     if (_vector_loop_debug) {
4444       tty->print_cr("SuperWord::find_phi_for_mem_dep input node %d to load %d has no other outputs and edge mem->load cannot be removed",
4445         mem->_idx, ld->_idx);
4446       ld->dump();
4447       mem->dump();
4448     }
4449 #endif
4450     return NULL;
4451   }
4452   if (!in_bb(mem) || same_generation(mem, ld)) {
4453 #ifndef PRODUCT
4454     if (_vector_loop_debug) {
4455       tty->print_cr("SuperWord::find_phi_for_mem_dep _clone_map.gen(mem->_idx)=%d",
4456         _clone_map.gen(mem->_idx));
4457     }
4458 #endif
4459     return NULL; // does not depend on loop volatile node or depends on the same generation
4460   }
4461 
4462   //otherwise first node should depend on mem-phi
4463   Node* first = first_node(ld);
4464   assert(first->is_Load(), "must be Load");
4465   Node* phi = first->as_Load()->in(MemNode::Memory);
4466   if (!phi->is_Phi() || phi->bottom_type() != Type::MEMORY) {
4467 #ifndef PRODUCT
4468     if (_vector_loop_debug) {
4469       tty->print_cr("SuperWord::find_phi_for_mem_dep load is not vectorizable node, since it's `first` does not take input from mem phi");
4470       ld->dump();
4471       first->dump();
4472     }
4473 #endif
4474     return NULL;
4475   }
4476 
4477   Node* tail = 0;
4478   for (int m = 0; m < _mem_slice_head.length(); m++) {
4479     if (_mem_slice_head.at(m) == phi) {
4480       tail = _mem_slice_tail.at(m);
4481     }
4482   }
4483   if (tail == 0) { //test that found phi is in the list  _mem_slice_head
4484 #ifndef PRODUCT
4485     if (_vector_loop_debug) {
4486       tty->print_cr("SuperWord::find_phi_for_mem_dep load %d is not vectorizable node, its phi %d is not _mem_slice_head",
4487         ld->_idx, phi->_idx);
4488       ld->dump();
4489       phi->dump();
4490     }
4491 #endif
4492     return NULL;
4493   }
4494 
4495   // now all conditions are met
4496   return phi;
4497 }
4498 
4499 Node* SuperWord::first_node(Node* nd) {
4500   for (int ii = 0; ii < _iteration_first.length(); ii++) {
4501     Node* nnn = _iteration_first.at(ii);
4502     if (same_origin_idx(nnn, nd)) {
4503 #ifndef PRODUCT
4504       if (_vector_loop_debug) {
4505         tty->print_cr("SuperWord::first_node: %d is the first iteration node for %d (_clone_map.idx(nnn->_idx) = %d)",
4506           nnn->_idx, nd->_idx, _clone_map.idx(nnn->_idx));
4507       }
4508 #endif
4509       return nnn;
4510     }
4511   }
4512 
4513 #ifndef PRODUCT
4514   if (_vector_loop_debug) {
4515     tty->print_cr("SuperWord::first_node: did not find first iteration node for %d (_clone_map.idx(nd->_idx)=%d)",
4516       nd->_idx, _clone_map.idx(nd->_idx));
4517   }
4518 #endif
4519   return 0;
4520 }
4521 
4522 Node* SuperWord::last_node(Node* nd) {
4523   for (int ii = 0; ii < _iteration_last.length(); ii++) {
4524     Node* nnn = _iteration_last.at(ii);
4525     if (same_origin_idx(nnn, nd)) {
4526 #ifndef PRODUCT
4527       if (_vector_loop_debug) {
4528         tty->print_cr("SuperWord::last_node _clone_map.idx(nnn->_idx)=%d, _clone_map.idx(nd->_idx)=%d",
4529           _clone_map.idx(nnn->_idx), _clone_map.idx(nd->_idx));
4530       }
4531 #endif
4532       return nnn;
4533     }
4534   }
4535   return 0;
4536 }
4537 
4538 int SuperWord::mark_generations() {
4539   Node *ii_err = NULL, *tail_err = NULL;
4540   for (int i = 0; i < _mem_slice_head.length(); i++) {
4541     Node* phi  = _mem_slice_head.at(i);
4542     assert(phi->is_Phi(), "must be phi");
4543 
4544     Node* tail = _mem_slice_tail.at(i);
4545     if (_ii_last == -1) {
4546       tail_err = tail;
4547       _ii_last = _clone_map.gen(tail->_idx);
4548     }
4549     else if (_ii_last != _clone_map.gen(tail->_idx)) {
4550 #ifndef PRODUCT
4551       if (TraceSuperWord && Verbose) {
4552         tty->print_cr("SuperWord::mark_generations _ii_last error - found different generations in two tail nodes ");
4553         tail->dump();
4554         tail_err->dump();
4555       }
4556 #endif
4557       return -1;
4558     }
4559 
4560     // find first iteration in the loop
4561     for (DUIterator_Fast imax, i = phi->fast_outs(imax); i < imax; i++) {
4562       Node* ii = phi->fast_out(i);
4563       if (in_bb(ii) && ii->is_Store()) { // we speculate that normally Stores of one and one only generation have deps from mem phi
4564         if (_ii_first == -1) {
4565           ii_err = ii;
4566           _ii_first = _clone_map.gen(ii->_idx);
4567         } else if (_ii_first != _clone_map.gen(ii->_idx)) {
4568 #ifndef PRODUCT
4569           if (TraceSuperWord && Verbose) {
4570             tty->print_cr("SuperWord::mark_generations: _ii_first was found before and not equal to one in this node (%d)", _ii_first);
4571             ii->dump();
4572             if (ii_err!= 0) {
4573               ii_err->dump();
4574             }
4575           }
4576 #endif
4577           return -1; // this phi has Stores from different generations of unroll and cannot be simd/vectorized
4578         }
4579       }
4580     }//for (DUIterator_Fast imax,
4581   }//for (int i...
4582 
4583   if (_ii_first == -1 || _ii_last == -1) {
4584     if (TraceSuperWord && Verbose) {
4585       tty->print_cr("SuperWord::mark_generations unknown error, something vent wrong");
4586     }
4587     return -1; // something vent wrong
4588   }
4589   // collect nodes in the first and last generations
4590   assert(_iteration_first.length() == 0, "_iteration_first must be empty");
4591   assert(_iteration_last.length() == 0, "_iteration_last must be empty");
4592   for (int j = 0; j < _block.length(); j++) {
4593     Node* n = _block.at(j);
4594     node_idx_t gen = _clone_map.gen(n->_idx);
4595     if ((signed)gen == _ii_first) {
4596       _iteration_first.push(n);
4597     } else if ((signed)gen == _ii_last) {
4598       _iteration_last.push(n);
4599     }
4600   }
4601 
4602   // building order of iterations
4603   if (_ii_order.length() == 0 && ii_err != 0) {
4604     assert(in_bb(ii_err) && ii_err->is_Store(), "should be Store in bb");
4605     Node* nd = ii_err;
4606     while(_clone_map.gen(nd->_idx) != _ii_last) {
4607       _ii_order.push(_clone_map.gen(nd->_idx));
4608       bool found = false;
4609       for (DUIterator_Fast imax, i = nd->fast_outs(imax); i < imax; i++) {
4610         Node* use = nd->fast_out(i);
4611         if (same_origin_idx(use, nd) && use->as_Store()->in(MemNode::Memory) == nd) {
4612           found = true;
4613           nd = use;
4614           break;
4615         }
4616       }//for
4617 
4618       if (found == false) {
4619         if (TraceSuperWord && Verbose) {
4620           tty->print_cr("SuperWord::mark_generations: Cannot build order of iterations - no dependent Store for %d", nd->_idx);
4621         }
4622         _ii_order.clear();
4623         return -1;
4624       }
4625     } //while
4626     _ii_order.push(_clone_map.gen(nd->_idx));
4627   }
4628 
4629 #ifndef PRODUCT
4630   if (_vector_loop_debug) {
4631     tty->print_cr("SuperWord::mark_generations");
4632     tty->print_cr("First generation (%d) nodes:", _ii_first);
4633     for (int ii = 0; ii < _iteration_first.length(); ii++)  _iteration_first.at(ii)->dump();
4634     tty->print_cr("Last generation (%d) nodes:", _ii_last);
4635     for (int ii = 0; ii < _iteration_last.length(); ii++)  _iteration_last.at(ii)->dump();
4636     tty->print_cr(" ");
4637 
4638     tty->print("SuperWord::List of generations: ");
4639     for (int jj = 0; jj < _ii_order.length(); ++jj) {
4640       tty->print("%d:%d ", jj, _ii_order.at(jj));
4641     }
4642     tty->print_cr(" ");
4643   }
4644 #endif
4645 
4646   return _ii_first;
4647 }
4648 
4649 bool SuperWord::fix_commutative_inputs(Node* gold, Node* fix) {
4650   assert(gold->is_Add() && fix->is_Add() || gold->is_Mul() && fix->is_Mul(), "should be only Add or Mul nodes");
4651   assert(same_origin_idx(gold, fix), "should be clones of the same node");
4652   Node* gin1 = gold->in(1);
4653   Node* gin2 = gold->in(2);
4654   Node* fin1 = fix->in(1);
4655   Node* fin2 = fix->in(2);
4656   bool swapped = false;
4657 
4658   if (in_bb(gin1) && in_bb(gin2) && in_bb(fin1) && in_bb(fin1)) {
4659     if (same_origin_idx(gin1, fin1) &&
4660         same_origin_idx(gin2, fin2)) {
4661       return true; // nothing to fix
4662     }
4663     if (same_origin_idx(gin1, fin2) &&
4664         same_origin_idx(gin2, fin1)) {
4665       fix->swap_edges(1, 2);
4666       swapped = true;
4667     }
4668   }
4669   // at least one input comes from outside of bb
4670   if (gin1->_idx == fin1->_idx)  {
4671     return true; // nothing to fix
4672   }
4673   if (!swapped && (gin1->_idx == fin2->_idx || gin2->_idx == fin1->_idx))  { //swapping is expensive, check condition first
4674     fix->swap_edges(1, 2);
4675     swapped = true;
4676   }
4677 
4678   if (swapped) {
4679 #ifndef PRODUCT
4680     if (_vector_loop_debug) {
4681       tty->print_cr("SuperWord::fix_commutative_inputs: fixed node %d", fix->_idx);
4682     }
4683 #endif
4684     return true;
4685   }
4686 
4687   if (TraceSuperWord && Verbose) {
4688     tty->print_cr("SuperWord::fix_commutative_inputs: cannot fix node %d", fix->_idx);
4689   }
4690 
4691   return false;
4692 }
4693 
4694 bool SuperWord::pack_parallel() {
4695 #ifndef PRODUCT
4696   if (_vector_loop_debug) {
4697     tty->print_cr("SuperWord::pack_parallel: START");
4698   }
4699 #endif
4700 
4701   _packset.clear();
4702 
4703   for (int ii = 0; ii < _iteration_first.length(); ii++) {
4704     Node* nd = _iteration_first.at(ii);
4705     if (in_bb(nd) && (nd->is_Load() || nd->is_Store() || nd->is_Add() || nd->is_Mul())) {
4706       Node_List* pk = new Node_List();
4707       pk->push(nd);
4708       for (int gen = 1; gen < _ii_order.length(); ++gen) {
4709         for (int kk = 0; kk < _block.length(); kk++) {
4710           Node* clone = _block.at(kk);
4711           if (same_origin_idx(clone, nd) &&
4712               _clone_map.gen(clone->_idx) == _ii_order.at(gen)) {
4713             if (nd->is_Add() || nd->is_Mul()) {
4714               fix_commutative_inputs(nd, clone);
4715             }
4716             pk->push(clone);
4717             if (pk->size() == 4) {
4718               _packset.append(pk);
4719 #ifndef PRODUCT
4720               if (_vector_loop_debug) {
4721                 tty->print_cr("SuperWord::pack_parallel: added pack ");
4722                 pk->dump();
4723               }
4724 #endif
4725               if (_clone_map.gen(clone->_idx) != _ii_last) {
4726                 pk = new Node_List();
4727               }
4728             }
4729             break;
4730           }
4731         }
4732       }//for
4733     }//if
4734   }//for
4735 
4736 #ifndef PRODUCT
4737   if (_vector_loop_debug) {
4738     tty->print_cr("SuperWord::pack_parallel: END");
4739   }
4740 #endif
4741 
4742   return true;
4743 }
4744 
4745 bool SuperWord::hoist_loads_in_graph() {
4746   GrowableArray<Node*> loads;
4747 
4748 #ifndef PRODUCT
4749   if (_vector_loop_debug) {
4750     tty->print_cr("SuperWord::hoist_loads_in_graph: total number _mem_slice_head.length() = %d", _mem_slice_head.length());
4751   }
4752 #endif
4753 
4754   for (int i = 0; i < _mem_slice_head.length(); i++) {
4755     Node* n = _mem_slice_head.at(i);
4756     if ( !in_bb(n) || !n->is_Phi() || n->bottom_type() != Type::MEMORY) {
4757       if (TraceSuperWord && Verbose) {
4758         tty->print_cr("SuperWord::hoist_loads_in_graph: skipping unexpected node n=%d", n->_idx);
4759       }
4760       continue;
4761     }
4762 
4763 #ifndef PRODUCT
4764     if (_vector_loop_debug) {
4765       tty->print_cr("SuperWord::hoist_loads_in_graph: processing phi %d  = _mem_slice_head.at(%d);", n->_idx, i);
4766     }
4767 #endif
4768 
4769     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4770       Node* ld = n->fast_out(i);
4771       if (ld->is_Load() && ld->as_Load()->in(MemNode::Memory) == n && in_bb(ld)) {
4772         for (int i = 0; i < _block.length(); i++) {
4773           Node* ld2 = _block.at(i);
4774           if (ld2->is_Load() && same_origin_idx(ld, ld2) &&
4775               !same_generation(ld, ld2)) { // <= do not collect the first generation ld
4776 #ifndef PRODUCT
4777             if (_vector_loop_debug) {
4778               tty->print_cr("SuperWord::hoist_loads_in_graph: will try to hoist load ld2->_idx=%d, cloned from %d (ld->_idx=%d)",
4779                 ld2->_idx, _clone_map.idx(ld->_idx), ld->_idx);
4780             }
4781 #endif
4782             // could not do on-the-fly, since iterator is immutable
4783             loads.push(ld2);
4784           }
4785         }// for
4786       }//if
4787     }//for (DUIterator_Fast imax,
4788   }//for (int i = 0; i
4789 
4790   for (int i = 0; i < loads.length(); i++) {
4791     LoadNode* ld = loads.at(i)->as_Load();
4792     Node* phi = find_phi_for_mem_dep(ld);
4793     if (phi != NULL) {
4794 #ifndef PRODUCT
4795       if (_vector_loop_debug) {
4796         tty->print_cr("SuperWord::hoist_loads_in_graph replacing MemNode::Memory(%d) edge in %d with one from %d",
4797           MemNode::Memory, ld->_idx, phi->_idx);
4798       }
4799 #endif
4800       _igvn.replace_input_of(ld, MemNode::Memory, phi);
4801     }
4802   }//for
4803 
4804   restart(); // invalidate all basic structures, since we rebuilt the graph
4805 
4806   if (TraceSuperWord && Verbose) {
4807     tty->print_cr("\nSuperWord::hoist_loads_in_graph() the graph was rebuilt, all structures invalidated and need rebuild");
4808   }
4809 
4810   return true;
4811 }