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