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                  opc == Op_CountLeadingZerosI || opc == Op_CountLeadingZerosL ||
2569                  opc == Op_CountTrailingZerosI || opc == Op_CountTrailingZerosL) {
2570         assert(n->req() == 2, "only one input expected");
2571         Node* in = vector_opd(p, 1);
2572         vn = VectorNode::make(opc, in, NULL, vlen, velt_basic_type(n));
2573         vlen_in_bytes = vn->as_Vector()->length_in_bytes();
2574       } else if (opc == Op_ConvI2F || opc == Op_ConvL2D ||
2575                  opc == Op_ConvF2I || opc == Op_ConvD2L) {
2576         assert(n->req() == 2, "only one input expected");
2577         BasicType bt = velt_basic_type(n);
2578         int vopc = VectorNode::opcode(opc, bt);
2579         Node* in = vector_opd(p, 1);
2580         vn = VectorCastNode::make(vopc, in, bt, vlen);
2581         vlen_in_bytes = vn->as_Vector()->length_in_bytes();
2582       } else if (is_cmov_pack(p)) {
2583         if (cl->is_rce_post_loop()) {
2584           // do not refactor of flow in post loop context
2585           return false;
2586         }
2587         if (!n->is_CMove()) {
2588           continue;
2589         }
2590         // place here CMoveVDNode
2591         NOT_PRODUCT(if(is_trace_cmov()) {tty->print_cr("SWPointer::output: print before CMove vectorization"); print_loop(false);})
2592         Node* bol = n->in(CMoveNode::Condition);
2593         if (!bol->is_Bool() && bol->Opcode() == Op_ExtractI && bol->req() > 1 ) {
2594           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();})
2595           bol = bol->in(1); //may be ExtractNode
2596         }
2597 
2598         assert(bol->is_Bool(), "should be BoolNode - too late to bail out!");
2599         if (!bol->is_Bool()) {
2600           if (do_reserve_copy()) {
2601             NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: expected %d bool node, exiting SuperWord", bol->_idx); bol->dump();})
2602             return false; //and reverse to backup IG
2603           }
2604           ShouldNotReachHere();
2605         }
2606 
2607         int cond = (int)bol->as_Bool()->_test._test;
2608         Node* in_cc  = _igvn.intcon(cond);
2609         NOT_PRODUCT(if(is_trace_cmov()) {tty->print("SWPointer::output: created intcon in_cc node %d", in_cc->_idx); in_cc->dump();})
2610         Node* cc = bol->clone();
2611         cc->set_req(1, in_cc);
2612         NOT_PRODUCT(if(is_trace_cmov()) {tty->print("SWPointer::output: created bool cc node %d", cc->_idx); cc->dump();})
2613 
2614         Node* src1 = vector_opd(p, 2); //2=CMoveNode::IfFalse
2615         if (src1 == NULL) {
2616           if (do_reserve_copy()) {
2617             NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: src1 should not be NULL, exiting SuperWord");})
2618             return false; //and reverse to backup IG
2619           }
2620           ShouldNotReachHere();
2621         }
2622         Node* src2 = vector_opd(p, 3); //3=CMoveNode::IfTrue
2623         if (src2 == NULL) {
2624           if (do_reserve_copy()) {
2625             NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: src2 should not be NULL, exiting SuperWord");})
2626             return false; //and reverse to backup IG
2627           }
2628           ShouldNotReachHere();
2629         }
2630         BasicType bt = velt_basic_type(n);
2631         const TypeVect* vt = TypeVect::make(bt, vlen);
2632         assert(bt == T_FLOAT || bt == T_DOUBLE, "Only vectorization for FP cmovs is supported");
2633         if (bt == T_FLOAT) {
2634           vn = new CMoveVFNode(cc, src1, src2, vt);
2635         } else {
2636           assert(bt == T_DOUBLE, "Expected double");
2637           vn = new CMoveVDNode(cc, src1, src2, vt);
2638         }
2639         NOT_PRODUCT(if(is_trace_cmov()) {tty->print("SWPointer::output: created new CMove node %d: ", vn->_idx); vn->dump();})
2640       } else if (opc == Op_FmaD || opc == Op_FmaF) {
2641         // Promote operands to vector
2642         Node* in1 = vector_opd(p, 1);
2643         Node* in2 = vector_opd(p, 2);
2644         Node* in3 = vector_opd(p, 3);
2645         vn = VectorNode::make(opc, in1, in2, in3, vlen, velt_basic_type(n));
2646         vlen_in_bytes = vn->as_Vector()->length_in_bytes();
2647       } else {
2648         if (do_reserve_copy()) {
2649           NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: ShouldNotReachHere, exiting SuperWord");})
2650           return false; //and reverse to backup IG
2651         }
2652         ShouldNotReachHere();
2653       }
2654 
2655       assert(vn != NULL, "sanity");
2656       if (vn == NULL) {
2657         if (do_reserve_copy()){
2658           NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("SWPointer::output: got NULL node, cannot proceed, exiting SuperWord");})
2659           return false; //and reverse to backup IG
2660         }
2661         ShouldNotReachHere();
2662       }
2663 
2664       _block.at_put(i, vn);
2665       _igvn.register_new_node_with_optimizer(vn);
2666       _phase->set_ctrl(vn, _phase->get_ctrl(p->at(0)));
2667       for (uint j = 0; j < p->size(); j++) {
2668         Node* pm = p->at(j);
2669         _igvn.replace_node(pm, vn);
2670       }
2671       _igvn._worklist.push(vn);
2672 
2673       if (vlen > max_vlen) {
2674         max_vlen = vlen;
2675       }
2676       if (vlen_in_bytes > max_vlen_in_bytes) {
2677         max_vlen_in_bytes = vlen_in_bytes;
2678       }
2679 #ifdef ASSERT
2680       if (TraceNewVectors) {
2681         tty->print("new Vector node: ");
2682         vn->dump();
2683       }
2684 #endif
2685     }
2686   }//for (int i = 0; i < _block.length(); i++)
2687 
2688   if (max_vlen_in_bytes > C->max_vector_size()) {
2689     C->set_max_vector_size(max_vlen_in_bytes);
2690   }
2691   if (max_vlen_in_bytes > 0) {
2692     cl->mark_loop_vectorized();
2693   }
2694 
2695   if (SuperWordLoopUnrollAnalysis) {
2696     if (cl->has_passed_slp()) {
2697       uint slp_max_unroll_factor = cl->slp_max_unroll();
2698       if (slp_max_unroll_factor == max_vlen) {
2699         if (TraceSuperWordLoopUnrollAnalysis) {
2700           tty->print_cr("vector loop(unroll=%d, len=%d)\n", max_vlen, max_vlen_in_bytes*BitsPerByte);
2701         }
2702 
2703         // For atomic unrolled loops which are vector mapped, instigate more unrolling
2704         cl->set_notpassed_slp();
2705         if (cl->is_main_loop()) {
2706           // if vector resources are limited, do not allow additional unrolling, also
2707           // do not unroll more on pure vector loops which were not reduced so that we can
2708           // program the post loop to single iteration execution.
2709           if (Matcher::float_pressure_limit() > 8) {
2710             C->set_major_progress();
2711             cl->mark_do_unroll_only();
2712           }
2713         }
2714         if (cl->is_rce_post_loop() && do_reserve_copy()) {
2715           cl->mark_is_multiversioned();
2716         }
2717       }
2718     }
2719   }
2720 
2721   if (do_reserve_copy()) {
2722     make_reversable.use_new();
2723   }
2724   NOT_PRODUCT(if(is_trace_loop_reverse()) {tty->print_cr("\n Final loop after SuperWord"); print_loop(true);})
2725   return true;
2726 }
2727 
2728 //-------------------------create_post_loop_vmask-------------------------
2729 // Check the post loop vectorizability and create a vector mask if yes.
2730 // Return NULL to bail out if post loop is not vectorizable.
2731 Node* SuperWord::create_post_loop_vmask() {
2732   CountedLoopNode *cl = lpt()->_head->as_CountedLoop();
2733   assert(cl->is_rce_post_loop(), "Must be an rce post loop");
2734   assert(!cl->is_reduction_loop(), "no vector reduction in post loop");
2735   assert(abs(cl->stride_con()) == 1, "post loop stride can only be +/-1");
2736 
2737   // Collect vector element types of all post loop packs. Also collect
2738   // superword pointers of each memory access operation if the address
2739   // expression is supported. (Note that vectorizable post loop should
2740   // only have positive scale in counting-up loop and negative scale in
2741   // counting-down loop.) Collected SWPointer(s) are also used for data
2742   // dependence check next.
2743   VectorElementSizeStats stats(_arena);
2744   GrowableArray<SWPointer*> swptrs(_arena, _packset.length(), 0, NULL);
2745   for (int i = 0; i < _packset.length(); i++) {
2746     Node_List* p = _packset.at(i);
2747     assert(p->size() == 1, "all post loop packs should be singleton");
2748     Node* n = p->at(0);
2749     BasicType bt = velt_basic_type(n);
2750     if (!is_java_primitive(bt)) {
2751       return NULL;
2752     }
2753     if (n->is_Mem()) {
2754       SWPointer* mem_p = new (_arena) SWPointer(n->as_Mem(), this, NULL, false);
2755       // For each memory access, we check if the scale (in bytes) in its
2756       // address expression is equal to the data size times loop stride.
2757       // With this, Only positive scales exist in counting-up loops and
2758       // negative scales exist in counting-down loops.
2759       if (mem_p->scale_in_bytes() != type2aelembytes(bt) * cl->stride_con()) {
2760         return NULL;
2761       }
2762       swptrs.append(mem_p);
2763     }
2764     stats.record_size(type2aelembytes(bt));
2765   }
2766 
2767   // Find the vector data type for generating vector masks. Currently we
2768   // don't support post loops with mixed vector data sizes
2769   int unique_size = stats.unique_size();
2770   BasicType vmask_bt;
2771   switch (unique_size) {
2772     case 1:  vmask_bt = T_BYTE; break;
2773     case 2:  vmask_bt = T_SHORT; break;
2774     case 4:  vmask_bt = T_INT; break;
2775     case 8:  vmask_bt = T_LONG; break;
2776     default: return NULL;
2777   }
2778 
2779   // Currently we can't remove this MaxVectorSize constraint. Without it,
2780   // it's not guaranteed that the RCE'd post loop runs at most "vlen - 1"
2781   // iterations, because the vector drain loop may not be cloned from the
2782   // vectorized main loop. We should re-engineer PostLoopMultiversioning
2783   // to fix this problem.
2784   int vlen = cl->slp_max_unroll();
2785   if (unique_size * vlen != MaxVectorSize) {
2786     return NULL;
2787   }
2788 
2789   // Bail out if target doesn't support mask generator or masked load/store
2790   if (!Matcher::match_rule_supported_vector(Op_LoadVectorMasked, vlen, vmask_bt)  ||
2791       !Matcher::match_rule_supported_vector(Op_StoreVectorMasked, vlen, vmask_bt) ||
2792       !Matcher::match_rule_supported_vector(Op_VectorMaskGen, vlen, vmask_bt)) {
2793     return NULL;
2794   }
2795 
2796   // Bail out if potential data dependence exists between memory accesses
2797   if (SWPointer::has_potential_dependence(swptrs)) {
2798     return NULL;
2799   }
2800 
2801   // Create vector mask with the post loop trip count. Note there's another
2802   // vector drain loop which is cloned from main loop before super-unrolling
2803   // so the scalar post loop runs at most vlen-1 trips. Hence, this version
2804   // only runs at most 1 iteration after vector mask transformation.
2805   Node* trip_cnt;
2806   Node* new_incr;
2807   if (cl->stride_con() > 0) {
2808     trip_cnt = new SubINode(cl->limit(), cl->init_trip());
2809     new_incr = new AddINode(cl->phi(), trip_cnt);
2810   } else {
2811     trip_cnt = new SubINode(cl->init_trip(), cl->limit());
2812     new_incr = new SubINode(cl->phi(), trip_cnt);
2813   }
2814   _igvn.register_new_node_with_optimizer(trip_cnt);
2815   _igvn.register_new_node_with_optimizer(new_incr);
2816   _igvn.replace_node(cl->incr(), new_incr);
2817   Node* length = new ConvI2LNode(trip_cnt);
2818   _igvn.register_new_node_with_optimizer(length);
2819   Node* vmask = VectorMaskGenNode::make(length, vmask_bt);
2820   _igvn.register_new_node_with_optimizer(vmask);
2821 
2822   // Remove exit test to transform 1-iteration loop to straight-line code.
2823   // This results in redundant cmp+branch instructions been eliminated.
2824   Node *cl_exit = cl->loopexit();
2825   _igvn.replace_input_of(cl_exit, 1, _igvn.intcon(0));
2826   return vmask;
2827 }
2828 
2829 //------------------------------vector_opd---------------------------
2830 // Create a vector operand for the nodes in pack p for operand: in(opd_idx)
2831 Node* SuperWord::vector_opd(Node_List* p, int opd_idx) {
2832   Node* p0 = p->at(0);
2833   uint vlen = p->size();
2834   Node* opd = p0->in(opd_idx);
2835   CountedLoopNode *cl = lpt()->_head->as_CountedLoop();
2836 
2837   if (cl->is_rce_post_loop()) {
2838     // override vlen with the main loops vector length
2839     vlen = cl->slp_max_unroll();
2840   }
2841 
2842   if (same_inputs(p, opd_idx)) {
2843     if (opd->is_Vector() || opd->is_LoadVector()) {
2844       assert(((opd_idx != 2) || !VectorNode::is_shift(p0)), "shift's count can't be vector");
2845       if (opd_idx == 2 && VectorNode::is_shift(p0)) {
2846         NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("shift's count can't be vector");})
2847         return NULL;
2848       }
2849       return opd; // input is matching vector
2850     }
2851     if ((opd_idx == 2) && VectorNode::is_shift(p0)) {
2852       Compile* C = _phase->C;
2853       Node* cnt = opd;
2854       // Vector instructions do not mask shift count, do it here.
2855       juint mask = (p0->bottom_type() == TypeInt::INT) ? (BitsPerInt - 1) : (BitsPerLong - 1);
2856       const TypeInt* t = opd->find_int_type();
2857       if (t != NULL && t->is_con()) {
2858         juint shift = t->get_con();
2859         if (shift > mask) { // Unsigned cmp
2860           cnt = ConNode::make(TypeInt::make(shift & mask));
2861         }
2862       } else {
2863         if (t == NULL || t->_lo < 0 || t->_hi > (int)mask) {
2864           cnt = ConNode::make(TypeInt::make(mask));
2865           _igvn.register_new_node_with_optimizer(cnt);
2866           cnt = new AndINode(opd, cnt);
2867           _igvn.register_new_node_with_optimizer(cnt);
2868           _phase->set_ctrl(cnt, _phase->get_ctrl(opd));
2869         }
2870         assert(opd->bottom_type()->isa_int(), "int type only");
2871         if (!opd->bottom_type()->isa_int()) {
2872           NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("Should be int type only");})
2873           return NULL;
2874         }
2875       }
2876       // Move shift count into vector register.
2877       cnt = VectorNode::shift_count(p0->Opcode(), cnt, vlen, velt_basic_type(p0));
2878       _igvn.register_new_node_with_optimizer(cnt);
2879       _phase->set_ctrl(cnt, _phase->get_ctrl(opd));
2880       return cnt;
2881     }
2882     assert(!opd->is_StoreVector(), "such vector is not expected here");
2883     if (opd->is_StoreVector()) {
2884       NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("StoreVector is not expected here");})
2885       return NULL;
2886     }
2887     // Convert scalar input to vector with the same number of elements as
2888     // p0's vector. Use p0's type because size of operand's container in
2889     // vector should match p0's size regardless operand's size.
2890     const Type* p0_t = NULL;
2891     VectorNode* vn = NULL;
2892     if (opd_idx == 2 && VectorNode::is_scalar_rotate(p0)) {
2893        Node* conv = opd;
2894        p0_t =  TypeInt::INT;
2895        if (p0->bottom_type()->isa_long()) {
2896          p0_t = TypeLong::LONG;
2897          conv = new ConvI2LNode(opd);
2898          _igvn.register_new_node_with_optimizer(conv);
2899          _phase->set_ctrl(conv, _phase->get_ctrl(opd));
2900        }
2901        vn = VectorNode::scalar2vector(conv, vlen, p0_t);
2902     } else {
2903        p0_t =  velt_type(p0);
2904        vn = VectorNode::scalar2vector(opd, vlen, p0_t);
2905     }
2906 
2907     _igvn.register_new_node_with_optimizer(vn);
2908     _phase->set_ctrl(vn, _phase->get_ctrl(opd));
2909 #ifdef ASSERT
2910     if (TraceNewVectors) {
2911       tty->print("new Vector node: ");
2912       vn->dump();
2913     }
2914 #endif
2915     return vn;
2916   }
2917 
2918   // Insert pack operation
2919   BasicType bt = velt_basic_type(p0);
2920   PackNode* pk = PackNode::make(opd, vlen, bt);
2921   DEBUG_ONLY( const BasicType opd_bt = opd->bottom_type()->basic_type(); )
2922 
2923   for (uint i = 1; i < vlen; i++) {
2924     Node* pi = p->at(i);
2925     Node* in = pi->in(opd_idx);
2926     assert(my_pack(in) == NULL, "Should already have been unpacked");
2927     if (my_pack(in) != NULL) {
2928       NOT_PRODUCT(if(is_trace_loop_reverse() || TraceLoopOpts) {tty->print_cr("Should already have been unpacked");})
2929       return NULL;
2930     }
2931     assert(opd_bt == in->bottom_type()->basic_type(), "all same type");
2932     pk->add_opd(in);
2933     if (VectorNode::is_muladds2i(pi)) {
2934       Node* in2 = pi->in(opd_idx + 2);
2935       assert(my_pack(in2) == NULL, "Should already have been unpacked");
2936       if (my_pack(in2) != NULL) {
2937         NOT_PRODUCT(if (is_trace_loop_reverse() || TraceLoopOpts) { tty->print_cr("Should already have been unpacked"); })
2938           return NULL;
2939       }
2940       assert(opd_bt == in2->bottom_type()->basic_type(), "all same type");
2941       pk->add_opd(in2);
2942     }
2943   }
2944   _igvn.register_new_node_with_optimizer(pk);
2945   _phase->set_ctrl(pk, _phase->get_ctrl(opd));
2946 #ifdef ASSERT
2947   if (TraceNewVectors) {
2948     tty->print("new Vector node: ");
2949     pk->dump();
2950   }
2951 #endif
2952   return pk;
2953 }
2954 
2955 //------------------------------insert_extracts---------------------------
2956 // If a use of pack p is not a vector use, then replace the
2957 // use with an extract operation.
2958 void SuperWord::insert_extracts(Node_List* p) {
2959   if (p->at(0)->is_Store()) return;
2960   assert(_n_idx_list.is_empty(), "empty (node,index) list");
2961 
2962   // Inspect each use of each pack member.  For each use that is
2963   // not a vector use, replace the use with an extract operation.
2964 
2965   for (uint i = 0; i < p->size(); i++) {
2966     Node* def = p->at(i);
2967     for (DUIterator_Fast jmax, j = def->fast_outs(jmax); j < jmax; j++) {
2968       Node* use = def->fast_out(j);
2969       for (uint k = 0; k < use->req(); k++) {
2970         Node* n = use->in(k);
2971         if (def == n) {
2972           Node_List* u_pk = my_pack(use);
2973           if ((u_pk == NULL || !is_cmov_pack(u_pk) || use->is_CMove()) && !is_vector_use(use, k)) {
2974               _n_idx_list.push(use, k);
2975           }
2976         }
2977       }
2978     }
2979   }
2980 
2981   while (_n_idx_list.is_nonempty()) {
2982     Node* use = _n_idx_list.node();
2983     int   idx = _n_idx_list.index();
2984     _n_idx_list.pop();
2985     Node* def = use->in(idx);
2986 
2987     if (def->is_reduction()) continue;
2988 
2989     // Insert extract operation
2990     _igvn.hash_delete(def);
2991     int def_pos = alignment(def) / data_size(def);
2992 
2993     Node* ex = ExtractNode::make(def, def_pos, velt_basic_type(def));
2994     _igvn.register_new_node_with_optimizer(ex);
2995     _phase->set_ctrl(ex, _phase->get_ctrl(def));
2996     _igvn.replace_input_of(use, idx, ex);
2997     _igvn._worklist.push(def);
2998 
2999     bb_insert_after(ex, bb_idx(def));
3000     set_velt_type(ex, velt_type(def));
3001   }
3002 }
3003 
3004 //------------------------------is_vector_use---------------------------
3005 // Is use->in(u_idx) a vector use?
3006 bool SuperWord::is_vector_use(Node* use, int u_idx) {
3007   Node_List* u_pk = my_pack(use);
3008   if (u_pk == NULL) return false;
3009   if (use->is_reduction()) return true;
3010   Node* def = use->in(u_idx);
3011   Node_List* d_pk = my_pack(def);
3012   if (d_pk == NULL) {
3013     // check for scalar promotion
3014     Node* n = u_pk->at(0)->in(u_idx);
3015     for (uint i = 1; i < u_pk->size(); i++) {
3016       if (u_pk->at(i)->in(u_idx) != n) return false;
3017     }
3018     return true;
3019   }
3020 
3021   if (VectorNode::is_muladds2i(use)) {
3022     // MulAddS2I takes shorts and produces ints - hence the special checks
3023     // on alignment and size.
3024     if (u_pk->size() * 2 != d_pk->size()) {
3025       return false;
3026     }
3027     for (uint i = 0; i < MIN2(d_pk->size(), u_pk->size()); i++) {
3028       Node* ui = u_pk->at(i);
3029       Node* di = d_pk->at(i);
3030       if (alignment(ui) != alignment(di) * 2) {
3031         return false;
3032       }
3033     }
3034     return true;
3035   }
3036 
3037   if (VectorNode::is_type_transition_long_to_int(use)) {
3038     // PopCountL/CountLeadingZerosL/CountTrailingZerosL takes long and produces
3039     // int - hence the special checks on alignment and size.
3040     if (u_pk->size() != d_pk->size()) {
3041       return false;
3042     }
3043     for (uint i = 0; i < MIN2(d_pk->size(), u_pk->size()); i++) {
3044       Node* ui = u_pk->at(i);
3045       Node* di = d_pk->at(i);
3046       if (alignment(ui) * 2 != alignment(di)) {
3047         return false;
3048       }
3049     }
3050     return true;
3051   }
3052 
3053 
3054   if (u_pk->size() != d_pk->size())
3055     return false;
3056   for (uint i = 0; i < u_pk->size(); i++) {
3057     Node* ui = u_pk->at(i);
3058     Node* di = d_pk->at(i);
3059     if (ui->in(u_idx) != di || alignment(ui) != alignment(di))
3060       return false;
3061   }
3062   return true;
3063 }
3064 
3065 //------------------------------construct_bb---------------------------
3066 // Construct reverse postorder list of block members
3067 bool SuperWord::construct_bb() {
3068   Node* entry = bb();
3069 
3070   assert(_stk.length() == 0,            "stk is empty");
3071   assert(_block.length() == 0,          "block is empty");
3072   assert(_data_entry.length() == 0,     "data_entry is empty");
3073   assert(_mem_slice_head.length() == 0, "mem_slice_head is empty");
3074   assert(_mem_slice_tail.length() == 0, "mem_slice_tail is empty");
3075 
3076   // Find non-control nodes with no inputs from within block,
3077   // create a temporary map from node _idx to bb_idx for use
3078   // by the visited and post_visited sets,
3079   // and count number of nodes in block.
3080   int bb_ct = 0;
3081   for (uint i = 0; i < lpt()->_body.size(); i++) {
3082     Node *n = lpt()->_body.at(i);
3083     set_bb_idx(n, i); // Create a temporary map
3084     if (in_bb(n)) {
3085       if (n->is_LoadStore() || n->is_MergeMem() ||
3086           (n->is_Proj() && !n->as_Proj()->is_CFG())) {
3087         // Bailout if the loop has LoadStore, MergeMem or data Proj
3088         // nodes. Superword optimization does not work with them.
3089         return false;
3090       }
3091       bb_ct++;
3092       if (!n->is_CFG()) {
3093         bool found = false;
3094         for (uint j = 0; j < n->req(); j++) {
3095           Node* def = n->in(j);
3096           if (def && in_bb(def)) {
3097             found = true;
3098             break;
3099           }
3100         }
3101         if (!found) {
3102           assert(n != entry, "can't be entry");
3103           _data_entry.push(n);
3104         }
3105       }
3106     }
3107   }
3108 
3109   // Find memory slices (head and tail)
3110   for (DUIterator_Fast imax, i = lp()->fast_outs(imax); i < imax; i++) {
3111     Node *n = lp()->fast_out(i);
3112     if (in_bb(n) && (n->is_Phi() && n->bottom_type() == Type::MEMORY)) {
3113       Node* n_tail  = n->in(LoopNode::LoopBackControl);
3114       if (n_tail != n->in(LoopNode::EntryControl)) {
3115         if (!n_tail->is_Mem()) {
3116           assert(n_tail->is_Mem(), "unexpected node for memory slice: %s", n_tail->Name());
3117           return false; // Bailout
3118         }
3119         _mem_slice_head.push(n);
3120         _mem_slice_tail.push(n_tail);
3121       }
3122     }
3123   }
3124 
3125   // Create an RPO list of nodes in block
3126 
3127   visited_clear();
3128   post_visited_clear();
3129 
3130   // Push all non-control nodes with no inputs from within block, then control entry
3131   for (int j = 0; j < _data_entry.length(); j++) {
3132     Node* n = _data_entry.at(j);
3133     visited_set(n);
3134     _stk.push(n);
3135   }
3136   visited_set(entry);
3137   _stk.push(entry);
3138 
3139   // Do a depth first walk over out edges
3140   int rpo_idx = bb_ct - 1;
3141   int size;
3142   int reduction_uses = 0;
3143   while ((size = _stk.length()) > 0) {
3144     Node* n = _stk.top(); // Leave node on stack
3145     if (!visited_test_set(n)) {
3146       // forward arc in graph
3147     } else if (!post_visited_test(n)) {
3148       // cross or back arc
3149       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3150         Node *use = n->fast_out(i);
3151         if (in_bb(use) && !visited_test(use) &&
3152             // Don't go around backedge
3153             (!use->is_Phi() || n == entry)) {
3154           if (use->is_reduction()) {
3155             // First see if we can map the reduction on the given system we are on, then
3156             // make a data entry operation for each reduction we see.
3157             BasicType bt = use->bottom_type()->basic_type();
3158             if (ReductionNode::implemented(use->Opcode(), Matcher::min_vector_size(bt), bt)) {
3159               reduction_uses++;
3160             }
3161           }
3162           _stk.push(use);
3163         }
3164       }
3165       if (_stk.length() == size) {
3166         // There were no additional uses, post visit node now
3167         _stk.pop(); // Remove node from stack
3168         assert(rpo_idx >= 0, "");
3169         _block.at_put_grow(rpo_idx, n);
3170         rpo_idx--;
3171         post_visited_set(n);
3172         assert(rpo_idx >= 0 || _stk.is_empty(), "");
3173       }
3174     } else {
3175       _stk.pop(); // Remove post-visited node from stack
3176     }
3177   }//while
3178 
3179   int ii_current = -1;
3180   unsigned int load_idx = (unsigned int)-1;
3181   // Build iterations order if needed
3182   bool build_ii_order = _do_vector_loop_experimental && _ii_order.is_empty();
3183   // Create real map of block indices for nodes
3184   for (int j = 0; j < _block.length(); j++) {
3185     Node* n = _block.at(j);
3186     set_bb_idx(n, j);
3187     if (build_ii_order && n->is_Load()) {
3188       if (ii_current == -1) {
3189         ii_current = _clone_map.gen(n->_idx);
3190         _ii_order.push(ii_current);
3191         load_idx = _clone_map.idx(n->_idx);
3192       } else if (_clone_map.idx(n->_idx) == load_idx && _clone_map.gen(n->_idx) != ii_current) {
3193         ii_current = _clone_map.gen(n->_idx);
3194         _ii_order.push(ii_current);
3195       }
3196     }
3197   }//for
3198 
3199   // Ensure extra info is allocated.
3200   initialize_bb();
3201 
3202 #ifndef PRODUCT
3203   if (_vector_loop_debug && _ii_order.length() > 0) {
3204     tty->print("SuperWord::construct_bb: List of generations: ");
3205     for (int jj = 0; jj < _ii_order.length(); ++jj) {
3206       tty->print("  %d:%d", jj, _ii_order.at(jj));
3207     }
3208     tty->print_cr(" ");
3209   }
3210   if (TraceSuperWord) {
3211     print_bb();
3212     tty->print_cr("\ndata entry nodes: %s", _data_entry.length() > 0 ? "" : "NONE");
3213     for (int m = 0; m < _data_entry.length(); m++) {
3214       tty->print("%3d ", m);
3215       _data_entry.at(m)->dump();
3216     }
3217     tty->print_cr("\nmemory slices: %s", _mem_slice_head.length() > 0 ? "" : "NONE");
3218     for (int m = 0; m < _mem_slice_head.length(); m++) {
3219       tty->print("%3d ", m); _mem_slice_head.at(m)->dump();
3220       tty->print("    ");    _mem_slice_tail.at(m)->dump();
3221     }
3222   }
3223 #endif
3224   assert(rpo_idx == -1 && bb_ct == _block.length(), "all block members found");
3225   return (_mem_slice_head.length() > 0) || (reduction_uses > 0) || (_data_entry.length() > 0);
3226 }
3227 
3228 //------------------------------initialize_bb---------------------------
3229 // Initialize per node info
3230 void SuperWord::initialize_bb() {
3231   Node* last = _block.at(_block.length() - 1);
3232   grow_node_info(bb_idx(last));
3233 }
3234 
3235 //------------------------------bb_insert_after---------------------------
3236 // Insert n into block after pos
3237 void SuperWord::bb_insert_after(Node* n, int pos) {
3238   int n_pos = pos + 1;
3239   // Make room
3240   for (int i = _block.length() - 1; i >= n_pos; i--) {
3241     _block.at_put_grow(i+1, _block.at(i));
3242   }
3243   for (int j = _node_info.length() - 1; j >= n_pos; j--) {
3244     _node_info.at_put_grow(j+1, _node_info.at(j));
3245   }
3246   // Set value
3247   _block.at_put_grow(n_pos, n);
3248   _node_info.at_put_grow(n_pos, SWNodeInfo::initial);
3249   // Adjust map from node->_idx to _block index
3250   for (int i = n_pos; i < _block.length(); i++) {
3251     set_bb_idx(_block.at(i), i);
3252   }
3253 }
3254 
3255 //------------------------------compute_max_depth---------------------------
3256 // Compute max depth for expressions from beginning of block
3257 // Use to prune search paths during test for independence.
3258 void SuperWord::compute_max_depth() {
3259   int ct = 0;
3260   bool again;
3261   do {
3262     again = false;
3263     for (int i = 0; i < _block.length(); i++) {
3264       Node* n = _block.at(i);
3265       if (!n->is_Phi()) {
3266         int d_orig = depth(n);
3267         int d_in   = 0;
3268         for (DepPreds preds(n, _dg); !preds.done(); preds.next()) {
3269           Node* pred = preds.current();
3270           if (in_bb(pred)) {
3271             d_in = MAX2(d_in, depth(pred));
3272           }
3273         }
3274         if (d_in + 1 != d_orig) {
3275           set_depth(n, d_in + 1);
3276           again = true;
3277         }
3278       }
3279     }
3280     ct++;
3281   } while (again);
3282 
3283   if (TraceSuperWord && Verbose) {
3284     tty->print_cr("compute_max_depth iterated: %d times", ct);
3285   }
3286 }
3287 
3288 //-------------------------compute_vector_element_type-----------------------
3289 // Compute necessary vector element type for expressions
3290 // This propagates backwards a narrower integer type when the
3291 // upper bits of the value are not needed.
3292 // Example:  char a,b,c;  a = b + c;
3293 // Normally the type of the add is integer, but for packed character
3294 // operations the type of the add needs to be char.
3295 void SuperWord::compute_vector_element_type() {
3296   if (TraceSuperWord && Verbose) {
3297     tty->print_cr("\ncompute_velt_type:");
3298   }
3299 
3300   // Initial type
3301   for (int i = 0; i < _block.length(); i++) {
3302     Node* n = _block.at(i);
3303     set_velt_type(n, container_type(n));
3304   }
3305 
3306   // Propagate integer narrowed type backwards through operations
3307   // that don't depend on higher order bits
3308   for (int i = _block.length() - 1; i >= 0; i--) {
3309     Node* n = _block.at(i);
3310     // Only integer types need be examined
3311     const Type* vtn = velt_type(n);
3312     if (vtn->basic_type() == T_INT) {
3313       uint start, end;
3314       VectorNode::vector_operands(n, &start, &end);
3315 
3316       for (uint j = start; j < end; j++) {
3317         Node* in  = n->in(j);
3318         // Don't propagate through a memory
3319         if (!in->is_Mem() && in_bb(in) && velt_type(in)->basic_type() == T_INT &&
3320             data_size(n) < data_size(in)) {
3321           bool same_type = true;
3322           for (DUIterator_Fast kmax, k = in->fast_outs(kmax); k < kmax; k++) {
3323             Node *use = in->fast_out(k);
3324             if (!in_bb(use) || !same_velt_type(use, n)) {
3325               same_type = false;
3326               break;
3327             }
3328           }
3329           if (same_type) {
3330             // In any Java arithmetic operation, operands of small integer types
3331             // (boolean, byte, char & short) should be promoted to int first. As
3332             // vector elements of small types don't have upper bits of int, for
3333             // RShiftI or AbsI operations, the compiler has to know the precise
3334             // signedness info of the 1st operand. These operations shouldn't be
3335             // vectorized if the signedness info is imprecise.
3336             const Type* vt = vtn;
3337             int op = in->Opcode();
3338             if (VectorNode::is_shift_opcode(op) || op == Op_AbsI) {
3339               Node* load = in->in(1);
3340               if (load->is_Load() && in_bb(load) && (velt_type(load)->basic_type() == T_INT)) {
3341                 // Only Load nodes distinguish signed (LoadS/LoadB) and unsigned
3342                 // (LoadUS/LoadUB) values. Store nodes only have one version.
3343                 vt = velt_type(load);
3344               } else if (op != Op_LShiftI) {
3345                 // Widen type to int to avoid the creation of vector nodes. Note
3346                 // that left shifts work regardless of the signedness.
3347                 vt = TypeInt::INT;
3348               }
3349             }
3350             set_velt_type(in, vt);
3351           }
3352         }
3353       }
3354     }
3355   }
3356 #ifndef PRODUCT
3357   if (TraceSuperWord && Verbose) {
3358     for (int i = 0; i < _block.length(); i++) {
3359       Node* n = _block.at(i);
3360       velt_type(n)->dump();
3361       tty->print("\t");
3362       n->dump();
3363     }
3364   }
3365 #endif
3366 }
3367 
3368 //------------------------------memory_alignment---------------------------
3369 // Alignment within a vector memory reference
3370 int SuperWord::memory_alignment(MemNode* s, int iv_adjust) {
3371 #ifndef PRODUCT
3372   if ((TraceSuperWord && Verbose) || is_trace_alignment()) {
3373     tty->print("SuperWord::memory_alignment within a vector memory reference for %d:  ", s->_idx); s->dump();
3374   }
3375 #endif
3376   NOT_PRODUCT(SWPointer::Tracer::Depth ddd(0);)
3377   SWPointer p(s, this, NULL, false);
3378   if (!p.valid()) {
3379     NOT_PRODUCT(if(is_trace_alignment()) tty->print_cr("SWPointer::memory_alignment: SWPointer p invalid, return bottom_align");)
3380     return bottom_align;
3381   }
3382   int vw = get_vw_bytes_special(s);
3383   if (vw < 2) {
3384     NOT_PRODUCT(if(is_trace_alignment()) tty->print_cr("SWPointer::memory_alignment: vector_width_in_bytes < 2, return bottom_align");)
3385     return bottom_align; // No vectors for this type
3386   }
3387   int offset  = p.offset_in_bytes();
3388   offset     += iv_adjust*p.memory_size();
3389   int off_rem = offset % vw;
3390   int off_mod = off_rem >= 0 ? off_rem : off_rem + vw;
3391 #ifndef PRODUCT
3392   if ((TraceSuperWord && Verbose) || is_trace_alignment()) {
3393     tty->print_cr("SWPointer::memory_alignment: off_rem = %d, off_mod = %d", off_rem, off_mod);
3394   }
3395 #endif
3396   return off_mod;
3397 }
3398 
3399 //---------------------------container_type---------------------------
3400 // Smallest type containing range of values
3401 const Type* SuperWord::container_type(Node* n) {
3402   if (n->is_Mem()) {
3403     BasicType bt = n->as_Mem()->memory_type();
3404     if (n->is_Store() && (bt == T_CHAR)) {
3405       // Use T_SHORT type instead of T_CHAR for stored values because any
3406       // preceding arithmetic operation extends values to signed Int.
3407       bt = T_SHORT;
3408     }
3409     if (n->Opcode() == Op_LoadUB) {
3410       // Adjust type for unsigned byte loads, it is important for right shifts.
3411       // T_BOOLEAN is used because there is no basic type representing type
3412       // TypeInt::UBYTE. Use of T_BOOLEAN for vectors is fine because only
3413       // size (one byte) and sign is important.
3414       bt = T_BOOLEAN;
3415     }
3416     return Type::get_const_basic_type(bt);
3417   }
3418   const Type* t = _igvn.type(n);
3419   if (t->basic_type() == T_INT) {
3420     // A narrow type of arithmetic operations will be determined by
3421     // propagating the type of memory operations.
3422     return TypeInt::INT;
3423   }
3424   return t;
3425 }
3426 
3427 bool SuperWord::same_velt_type(Node* n1, Node* n2) {
3428   const Type* vt1 = velt_type(n1);
3429   const Type* vt2 = velt_type(n2);
3430   if (vt1->basic_type() == T_INT && vt2->basic_type() == T_INT) {
3431     // Compare vectors element sizes for integer types.
3432     return data_size(n1) == data_size(n2);
3433   }
3434   return vt1 == vt2;
3435 }
3436 
3437 //------------------------------in_packset---------------------------
3438 // Are s1 and s2 in a pack pair and ordered as s1,s2?
3439 bool SuperWord::in_packset(Node* s1, Node* s2) {
3440   for (int i = 0; i < _packset.length(); i++) {
3441     Node_List* p = _packset.at(i);
3442     assert(p->size() == 2, "must be");
3443     if (p->at(0) == s1 && p->at(p->size()-1) == s2) {
3444       return true;
3445     }
3446   }
3447   return false;
3448 }
3449 
3450 //------------------------------in_pack---------------------------
3451 // Is s in pack p?
3452 Node_List* SuperWord::in_pack(Node* s, Node_List* p) {
3453   for (uint i = 0; i < p->size(); i++) {
3454     if (p->at(i) == s) {
3455       return p;
3456     }
3457   }
3458   return NULL;
3459 }
3460 
3461 //------------------------------remove_pack_at---------------------------
3462 // Remove the pack at position pos in the packset
3463 void SuperWord::remove_pack_at(int pos) {
3464   Node_List* p = _packset.at(pos);
3465   for (uint i = 0; i < p->size(); i++) {
3466     Node* s = p->at(i);
3467     set_my_pack(s, NULL);
3468   }
3469   _packset.remove_at(pos);
3470 }
3471 
3472 void SuperWord::packset_sort(int n) {
3473   // simple bubble sort so that we capitalize with O(n) when its already sorted
3474   while (n != 0) {
3475     bool swapped = false;
3476     for (int i = 1; i < n; i++) {
3477       Node_List* q_low = _packset.at(i-1);
3478       Node_List* q_i = _packset.at(i);
3479 
3480       // only swap when we find something to swap
3481       if (alignment(q_low->at(0)) > alignment(q_i->at(0))) {
3482         Node_List* t = q_i;
3483         *(_packset.adr_at(i)) = q_low;
3484         *(_packset.adr_at(i-1)) = q_i;
3485         swapped = true;
3486       }
3487     }
3488     if (swapped == false) break;
3489     n--;
3490   }
3491 }
3492 
3493 //------------------------------executed_first---------------------------
3494 // Return the node executed first in pack p.  Uses the RPO block list
3495 // to determine order.
3496 Node* SuperWord::executed_first(Node_List* p) {
3497   Node* n = p->at(0);
3498   int n_rpo = bb_idx(n);
3499   for (uint i = 1; i < p->size(); i++) {
3500     Node* s = p->at(i);
3501     int s_rpo = bb_idx(s);
3502     if (s_rpo < n_rpo) {
3503       n = s;
3504       n_rpo = s_rpo;
3505     }
3506   }
3507   return n;
3508 }
3509 
3510 //------------------------------executed_last---------------------------
3511 // Return the node executed last in pack p.
3512 Node* SuperWord::executed_last(Node_List* p) {
3513   Node* n = p->at(0);
3514   int n_rpo = bb_idx(n);
3515   for (uint i = 1; i < p->size(); i++) {
3516     Node* s = p->at(i);
3517     int s_rpo = bb_idx(s);
3518     if (s_rpo > n_rpo) {
3519       n = s;
3520       n_rpo = s_rpo;
3521     }
3522   }
3523   return n;
3524 }
3525 
3526 LoadNode::ControlDependency SuperWord::control_dependency(Node_List* p) {
3527   LoadNode::ControlDependency dep = LoadNode::DependsOnlyOnTest;
3528   for (uint i = 0; i < p->size(); i++) {
3529     Node* n = p->at(i);
3530     assert(n->is_Load(), "only meaningful for loads");
3531     if (!n->depends_only_on_test()) {
3532       if (n->as_Load()->has_unknown_control_dependency() &&
3533           dep != LoadNode::Pinned) {
3534         // Upgrade to unknown control...
3535         dep = LoadNode::UnknownControl;
3536       } else {
3537         // Otherwise, we must pin it.
3538         dep = LoadNode::Pinned;
3539       }
3540     }
3541   }
3542   return dep;
3543 }
3544 
3545 
3546 //----------------------------align_initial_loop_index---------------------------
3547 // Adjust pre-loop limit so that in main loop, a load/store reference
3548 // to align_to_ref will be a position zero in the vector.
3549 //   (iv + k) mod vector_align == 0
3550 void SuperWord::align_initial_loop_index(MemNode* align_to_ref) {
3551   assert(lp()->is_main_loop(), "");
3552   CountedLoopEndNode* pre_end = pre_loop_end();
3553   Node* pre_opaq1 = pre_end->limit();
3554   assert(pre_opaq1->Opcode() == Op_Opaque1, "");
3555   Opaque1Node* pre_opaq = (Opaque1Node*)pre_opaq1;
3556   Node* lim0 = pre_opaq->in(1);
3557 
3558   // Where we put new limit calculations
3559   Node* pre_ctrl = pre_loop_head()->in(LoopNode::EntryControl);
3560 
3561   // Ensure the original loop limit is available from the
3562   // pre-loop Opaque1 node.
3563   Node* orig_limit = pre_opaq->original_loop_limit();
3564   assert(orig_limit != NULL && _igvn.type(orig_limit) != Type::TOP, "");
3565 
3566   SWPointer align_to_ref_p(align_to_ref, this, NULL, false);
3567   assert(align_to_ref_p.valid(), "sanity");
3568 
3569   // Given:
3570   //     lim0 == original pre loop limit
3571   //     V == v_align (power of 2)
3572   //     invar == extra invariant piece of the address expression
3573   //     e == offset [ +/- invar ]
3574   //
3575   // When reassociating expressions involving '%' the basic rules are:
3576   //     (a - b) % k == 0   =>  a % k == b % k
3577   // and:
3578   //     (a + b) % k == 0   =>  a % k == (k - b) % k
3579   //
3580   // For stride > 0 && scale > 0,
3581   //   Derive the new pre-loop limit "lim" such that the two constraints:
3582   //     (1) lim = lim0 + N           (where N is some positive integer < V)
3583   //     (2) (e + lim) % V == 0
3584   //   are true.
3585   //
3586   //   Substituting (1) into (2),
3587   //     (e + lim0 + N) % V == 0
3588   //   solve for N:
3589   //     N = (V - (e + lim0)) % V
3590   //   substitute back into (1), so that new limit
3591   //     lim = lim0 + (V - (e + lim0)) % V
3592   //
3593   // For stride > 0 && scale < 0
3594   //   Constraints:
3595   //     lim = lim0 + N
3596   //     (e - lim) % V == 0
3597   //   Solving for lim:
3598   //     (e - lim0 - N) % V == 0
3599   //     N = (e - lim0) % V
3600   //     lim = lim0 + (e - lim0) % V
3601   //
3602   // For stride < 0 && scale > 0
3603   //   Constraints:
3604   //     lim = lim0 - N
3605   //     (e + lim) % V == 0
3606   //   Solving for lim:
3607   //     (e + lim0 - N) % V == 0
3608   //     N = (e + lim0) % V
3609   //     lim = lim0 - (e + lim0) % V
3610   //
3611   // For stride < 0 && scale < 0
3612   //   Constraints:
3613   //     lim = lim0 - N
3614   //     (e - lim) % V == 0
3615   //   Solving for lim:
3616   //     (e - lim0 + N) % V == 0
3617   //     N = (V - (e - lim0)) % V
3618   //     lim = lim0 - (V - (e - lim0)) % V
3619 
3620   int vw = vector_width_in_bytes(align_to_ref);
3621   int stride   = iv_stride();
3622   int scale    = align_to_ref_p.scale_in_bytes();
3623   int elt_size = align_to_ref_p.memory_size();
3624   int v_align  = vw / elt_size;
3625   assert(v_align > 1, "sanity");
3626   int offset   = align_to_ref_p.offset_in_bytes() / elt_size;
3627   Node *offsn  = _igvn.intcon(offset);
3628 
3629   Node *e = offsn;
3630   if (align_to_ref_p.invar() != NULL) {
3631     // incorporate any extra invariant piece producing (offset +/- invar) >>> log2(elt)
3632     Node* log2_elt = _igvn.intcon(exact_log2(elt_size));
3633     Node* invar = align_to_ref_p.invar();
3634     if (_igvn.type(invar)->isa_long()) {
3635       // Computations are done % (vector width/element size) so it's
3636       // safe to simply convert invar to an int and loose the upper 32
3637       // bit half.
3638       invar = new ConvL2INode(invar);
3639       _igvn.register_new_node_with_optimizer(invar);
3640     }
3641     Node* invar_scale = align_to_ref_p.invar_scale();
3642     if (invar_scale != NULL) {
3643       invar = new LShiftINode(invar, invar_scale);
3644       _igvn.register_new_node_with_optimizer(invar);
3645     }
3646     Node* aref = new URShiftINode(invar, log2_elt);
3647     _igvn.register_new_node_with_optimizer(aref);
3648     _phase->set_ctrl(aref, pre_ctrl);
3649     if (align_to_ref_p.negate_invar()) {
3650       e = new SubINode(e, aref);
3651     } else {
3652       e = new AddINode(e, aref);
3653     }
3654     _igvn.register_new_node_with_optimizer(e);
3655     _phase->set_ctrl(e, pre_ctrl);
3656   }
3657   if (vw > ObjectAlignmentInBytes || align_to_ref_p.base()->is_top()) {
3658     // incorporate base e +/- base && Mask >>> log2(elt)
3659     Node* xbase = new CastP2XNode(NULL, align_to_ref_p.adr());
3660     _igvn.register_new_node_with_optimizer(xbase);
3661 #ifdef _LP64
3662     xbase  = new ConvL2INode(xbase);
3663     _igvn.register_new_node_with_optimizer(xbase);
3664 #endif
3665     Node* mask = _igvn.intcon(vw-1);
3666     Node* masked_xbase  = new AndINode(xbase, mask);
3667     _igvn.register_new_node_with_optimizer(masked_xbase);
3668     Node* log2_elt = _igvn.intcon(exact_log2(elt_size));
3669     Node* bref     = new URShiftINode(masked_xbase, log2_elt);
3670     _igvn.register_new_node_with_optimizer(bref);
3671     _phase->set_ctrl(bref, pre_ctrl);
3672     e = new AddINode(e, bref);
3673     _igvn.register_new_node_with_optimizer(e);
3674     _phase->set_ctrl(e, pre_ctrl);
3675   }
3676 
3677   // compute e +/- lim0
3678   if (scale < 0) {
3679     e = new SubINode(e, lim0);
3680   } else {
3681     e = new AddINode(e, lim0);
3682   }
3683   _igvn.register_new_node_with_optimizer(e);
3684   _phase->set_ctrl(e, pre_ctrl);
3685 
3686   if (stride * scale > 0) {
3687     // compute V - (e +/- lim0)
3688     Node* va  = _igvn.intcon(v_align);
3689     e = new SubINode(va, e);
3690     _igvn.register_new_node_with_optimizer(e);
3691     _phase->set_ctrl(e, pre_ctrl);
3692   }
3693   // compute N = (exp) % V
3694   Node* va_msk = _igvn.intcon(v_align - 1);
3695   Node* N = new AndINode(e, va_msk);
3696   _igvn.register_new_node_with_optimizer(N);
3697   _phase->set_ctrl(N, pre_ctrl);
3698 
3699   //   substitute back into (1), so that new limit
3700   //     lim = lim0 + N
3701   Node* lim;
3702   if (stride < 0) {
3703     lim = new SubINode(lim0, N);
3704   } else {
3705     lim = new AddINode(lim0, N);
3706   }
3707   _igvn.register_new_node_with_optimizer(lim);
3708   _phase->set_ctrl(lim, pre_ctrl);
3709   Node* constrained =
3710     (stride > 0) ? (Node*) new MinINode(lim, orig_limit)
3711                  : (Node*) new MaxINode(lim, orig_limit);
3712   _igvn.register_new_node_with_optimizer(constrained);
3713   _phase->set_ctrl(constrained, pre_ctrl);
3714   _igvn.replace_input_of(pre_opaq, 1, constrained);
3715 }
3716 
3717 //----------------------------get_pre_loop_end---------------------------
3718 // Find pre loop end from main loop.  Returns null if none.
3719 CountedLoopEndNode* SuperWord::find_pre_loop_end(CountedLoopNode* cl) const {
3720   // The loop cannot be optimized if the graph shape at
3721   // the loop entry is inappropriate.
3722   if (cl->is_canonical_loop_entry() == NULL) {
3723     return NULL;
3724   }
3725 
3726   Node* p_f = cl->skip_predicates()->in(0)->in(0);
3727   if (!p_f->is_IfFalse()) return NULL;
3728   if (!p_f->in(0)->is_CountedLoopEnd()) return NULL;
3729   CountedLoopEndNode* pre_end = p_f->in(0)->as_CountedLoopEnd();
3730   CountedLoopNode* loop_node = pre_end->loopnode();
3731   if (loop_node == NULL || !loop_node->is_pre_loop()) return NULL;
3732   return pre_end;
3733 }
3734 
3735 //------------------------------init---------------------------
3736 void SuperWord::init() {
3737   _dg.init();
3738   _packset.clear();
3739   _disjoint_ptrs.clear();
3740   _block.clear();
3741   _post_block.clear();
3742   _data_entry.clear();
3743   _mem_slice_head.clear();
3744   _mem_slice_tail.clear();
3745   _iteration_first.clear();
3746   _iteration_last.clear();
3747   _node_info.clear();
3748   _align_to_ref = NULL;
3749   _lpt = NULL;
3750   _lp = NULL;
3751   _bb = NULL;
3752   _iv = NULL;
3753   _race_possible = 0;
3754   _early_return = false;
3755   _num_work_vecs = 0;
3756   _num_reductions = 0;
3757 }
3758 
3759 //------------------------------restart---------------------------
3760 void SuperWord::restart() {
3761   _dg.init();
3762   _packset.clear();
3763   _disjoint_ptrs.clear();
3764   _block.clear();
3765   _post_block.clear();
3766   _data_entry.clear();
3767   _mem_slice_head.clear();
3768   _mem_slice_tail.clear();
3769   _node_info.clear();
3770 }
3771 
3772 //------------------------------print_packset---------------------------
3773 void SuperWord::print_packset() {
3774 #ifndef PRODUCT
3775   tty->print_cr("packset");
3776   for (int i = 0; i < _packset.length(); i++) {
3777     tty->print_cr("Pack: %d", i);
3778     Node_List* p = _packset.at(i);
3779     print_pack(p);
3780   }
3781 #endif
3782 }
3783 
3784 //------------------------------print_pack---------------------------
3785 void SuperWord::print_pack(Node_List* p) {
3786   for (uint i = 0; i < p->size(); i++) {
3787     print_stmt(p->at(i));
3788   }
3789 }
3790 
3791 //------------------------------print_bb---------------------------
3792 void SuperWord::print_bb() {
3793 #ifndef PRODUCT
3794   tty->print_cr("\nBlock");
3795   for (int i = 0; i < _block.length(); i++) {
3796     Node* n = _block.at(i);
3797     tty->print("%d ", i);
3798     if (n) {
3799       n->dump();
3800     }
3801   }
3802 #endif
3803 }
3804 
3805 //------------------------------print_stmt---------------------------
3806 void SuperWord::print_stmt(Node* s) {
3807 #ifndef PRODUCT
3808   tty->print(" align: %d \t", alignment(s));
3809   s->dump();
3810 #endif
3811 }
3812 
3813 //------------------------------blank---------------------------
3814 char* SuperWord::blank(uint depth) {
3815   static char blanks[101];
3816   assert(depth < 101, "too deep");
3817   for (uint i = 0; i < depth; i++) blanks[i] = ' ';
3818   blanks[depth] = '\0';
3819   return blanks;
3820 }
3821 
3822 
3823 //==============================SWPointer===========================
3824 #ifndef PRODUCT
3825 int SWPointer::Tracer::_depth = 0;
3826 #endif
3827 //----------------------------SWPointer------------------------
3828 SWPointer::SWPointer(MemNode* mem, SuperWord* slp, Node_Stack *nstack, bool analyze_only) :
3829   _mem(mem), _slp(slp),  _base(NULL),  _adr(NULL),
3830   _scale(0), _offset(0), _invar(NULL), _negate_invar(false),
3831   _invar_scale(NULL),
3832   _nstack(nstack), _analyze_only(analyze_only),
3833   _stack_idx(0)
3834 #ifndef PRODUCT
3835   , _tracer(slp)
3836 #endif
3837 {
3838   NOT_PRODUCT(_tracer.ctor_1(mem);)
3839 
3840   Node* adr = mem->in(MemNode::Address);
3841   if (!adr->is_AddP()) {
3842     assert(!valid(), "too complex");
3843     return;
3844   }
3845   // Match AddP(base, AddP(ptr, k*iv [+ invariant]), constant)
3846   Node* base = adr->in(AddPNode::Base);
3847   // The base address should be loop invariant
3848   if (is_loop_member(base)) {
3849     assert(!valid(), "base address is loop variant");
3850     return;
3851   }
3852   // unsafe references require misaligned vector access support
3853   if (base->is_top() && !Matcher::misaligned_vectors_ok()) {
3854     assert(!valid(), "unsafe access");
3855     return;
3856   }
3857 
3858   NOT_PRODUCT(if(_slp->is_trace_alignment()) _tracer.store_depth();)
3859   NOT_PRODUCT(_tracer.ctor_2(adr);)
3860 
3861   int i;
3862   for (i = 0; i < 3; i++) {
3863     NOT_PRODUCT(_tracer.ctor_3(adr, i);)
3864 
3865     if (!scaled_iv_plus_offset(adr->in(AddPNode::Offset))) {
3866       assert(!valid(), "too complex");
3867       return;
3868     }
3869     adr = adr->in(AddPNode::Address);
3870     NOT_PRODUCT(_tracer.ctor_4(adr, i);)
3871 
3872     if (base == adr || !adr->is_AddP()) {
3873       NOT_PRODUCT(_tracer.ctor_5(adr, base, i);)
3874       break; // stop looking at addp's
3875     }
3876   }
3877   if (is_loop_member(adr)) {
3878     assert(!valid(), "adr is loop variant");
3879     return;
3880   }
3881 
3882   if (!base->is_top() && adr != base) {
3883     assert(!valid(), "adr and base differ");
3884     return;
3885   }
3886 
3887   NOT_PRODUCT(if(_slp->is_trace_alignment()) _tracer.restore_depth();)
3888   NOT_PRODUCT(_tracer.ctor_6(mem);)
3889 
3890   _base = base;
3891   _adr  = adr;
3892   assert(valid(), "Usable");
3893 }
3894 
3895 // Following is used to create a temporary object during
3896 // the pattern match of an address expression.
3897 SWPointer::SWPointer(SWPointer* p) :
3898   _mem(p->_mem), _slp(p->_slp),  _base(NULL),  _adr(NULL),
3899   _scale(0), _offset(0), _invar(NULL), _negate_invar(false),
3900   _invar_scale(NULL),
3901   _nstack(p->_nstack), _analyze_only(p->_analyze_only),
3902   _stack_idx(p->_stack_idx)
3903   #ifndef PRODUCT
3904   , _tracer(p->_slp)
3905   #endif
3906 {}
3907 
3908 bool SWPointer::is_loop_member(Node* n) const {
3909   Node* n_c = phase()->get_ctrl(n);
3910   return lpt()->is_member(phase()->get_loop(n_c));
3911 }
3912 
3913 bool SWPointer::invariant(Node* n) const {
3914   NOT_PRODUCT(Tracer::Depth dd;)
3915   Node* n_c = phase()->get_ctrl(n);
3916   NOT_PRODUCT(_tracer.invariant_1(n, n_c);)
3917   bool is_not_member = !is_loop_member(n);
3918   if (is_not_member && _slp->lp()->is_main_loop()) {
3919     // 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
3920     // CountedLoopEndNode check because n_c is either part of the pre loop or between the pre and the main loop (illegal
3921     // invariant: Happens, for example, when n_c is a CastII node that prevents data nodes to flow above the main loop).
3922     return phase()->is_dominator(n_c, _slp->pre_loop_head());
3923   }
3924   return is_not_member;
3925 }
3926 
3927 //------------------------scaled_iv_plus_offset--------------------
3928 // Match: k*iv + offset
3929 // where: k is a constant that maybe zero, and
3930 //        offset is (k2 [+/- invariant]) where k2 maybe zero and invariant is optional
3931 bool SWPointer::scaled_iv_plus_offset(Node* n) {
3932   NOT_PRODUCT(Tracer::Depth ddd;)
3933   NOT_PRODUCT(_tracer.scaled_iv_plus_offset_1(n);)
3934 
3935   if (scaled_iv(n)) {
3936     NOT_PRODUCT(_tracer.scaled_iv_plus_offset_2(n);)
3937     return true;
3938   }
3939 
3940   if (offset_plus_k(n)) {
3941     NOT_PRODUCT(_tracer.scaled_iv_plus_offset_3(n);)
3942     return true;
3943   }
3944 
3945   int opc = n->Opcode();
3946   if (opc == Op_AddI) {
3947     if (offset_plus_k(n->in(2)) && scaled_iv_plus_offset(n->in(1))) {
3948       NOT_PRODUCT(_tracer.scaled_iv_plus_offset_4(n);)
3949       return true;
3950     }
3951     if (offset_plus_k(n->in(1)) && scaled_iv_plus_offset(n->in(2))) {
3952       NOT_PRODUCT(_tracer.scaled_iv_plus_offset_5(n);)
3953       return true;
3954     }
3955   } else if (opc == Op_SubI) {
3956     if (offset_plus_k(n->in(2), true) && scaled_iv_plus_offset(n->in(1))) {
3957       NOT_PRODUCT(_tracer.scaled_iv_plus_offset_6(n);)
3958       return true;
3959     }
3960     if (offset_plus_k(n->in(1)) && scaled_iv_plus_offset(n->in(2))) {
3961       _scale *= -1;
3962       NOT_PRODUCT(_tracer.scaled_iv_plus_offset_7(n);)
3963       return true;
3964     }
3965   }
3966 
3967   NOT_PRODUCT(_tracer.scaled_iv_plus_offset_8(n);)
3968   return false;
3969 }
3970 
3971 //----------------------------scaled_iv------------------------
3972 // Match: k*iv where k is a constant that's not zero
3973 bool SWPointer::scaled_iv(Node* n) {
3974   NOT_PRODUCT(Tracer::Depth ddd;)
3975   NOT_PRODUCT(_tracer.scaled_iv_1(n);)
3976 
3977   if (_scale != 0) { // already found a scale
3978     NOT_PRODUCT(_tracer.scaled_iv_2(n, _scale);)
3979     return false;
3980   }
3981 
3982   if (n == iv()) {
3983     _scale = 1;
3984     NOT_PRODUCT(_tracer.scaled_iv_3(n, _scale);)
3985     return true;
3986   }
3987   if (_analyze_only && (is_loop_member(n))) {
3988     _nstack->push(n, _stack_idx++);
3989   }
3990 
3991   int opc = n->Opcode();
3992   if (opc == Op_MulI) {
3993     if (n->in(1) == iv() && n->in(2)->is_Con()) {
3994       _scale = n->in(2)->get_int();
3995       NOT_PRODUCT(_tracer.scaled_iv_4(n, _scale);)
3996       return true;
3997     } else if (n->in(2) == iv() && n->in(1)->is_Con()) {
3998       _scale = n->in(1)->get_int();
3999       NOT_PRODUCT(_tracer.scaled_iv_5(n, _scale);)
4000       return true;
4001     }
4002   } else if (opc == Op_LShiftI) {
4003     if (n->in(1) == iv() && n->in(2)->is_Con()) {
4004       _scale = 1 << n->in(2)->get_int();
4005       NOT_PRODUCT(_tracer.scaled_iv_6(n, _scale);)
4006       return true;
4007     }
4008   } else if (opc == Op_ConvI2L || opc == Op_CastII) {
4009     if (scaled_iv_plus_offset(n->in(1))) {
4010       NOT_PRODUCT(_tracer.scaled_iv_7(n);)
4011       return true;
4012     }
4013   } else if (opc == Op_LShiftL && n->in(2)->is_Con()) {
4014     if (!has_iv() && _invar == NULL) {
4015       // Need to preserve the current _offset value, so
4016       // create a temporary object for this expression subtree.
4017       // Hacky, so should re-engineer the address pattern match.
4018       NOT_PRODUCT(Tracer::Depth dddd;)
4019       SWPointer tmp(this);
4020       NOT_PRODUCT(_tracer.scaled_iv_8(n, &tmp);)
4021 
4022       if (tmp.scaled_iv_plus_offset(n->in(1))) {
4023         int scale = n->in(2)->get_int();
4024         _scale   = tmp._scale  << scale;
4025         _offset += tmp._offset << scale;
4026         _invar = tmp._invar;
4027         if (_invar != NULL) {
4028           _negate_invar = tmp._negate_invar;
4029           _invar_scale = n->in(2);
4030         }
4031         NOT_PRODUCT(_tracer.scaled_iv_9(n, _scale, _offset, _invar, _negate_invar);)
4032         return true;
4033       }
4034     }
4035   }
4036   NOT_PRODUCT(_tracer.scaled_iv_10(n);)
4037   return false;
4038 }
4039 
4040 //----------------------------offset_plus_k------------------------
4041 // Match: offset is (k [+/- invariant])
4042 // where k maybe zero and invariant is optional, but not both.
4043 bool SWPointer::offset_plus_k(Node* n, bool negate) {
4044   NOT_PRODUCT(Tracer::Depth ddd;)
4045   NOT_PRODUCT(_tracer.offset_plus_k_1(n);)
4046 
4047   int opc = n->Opcode();
4048   if (opc == Op_ConI) {
4049     _offset += negate ? -(n->get_int()) : n->get_int();
4050     NOT_PRODUCT(_tracer.offset_plus_k_2(n, _offset);)
4051     return true;
4052   } else if (opc == Op_ConL) {
4053     // Okay if value fits into an int
4054     const TypeLong* t = n->find_long_type();
4055     if (t->higher_equal(TypeLong::INT)) {
4056       jlong loff = n->get_long();
4057       jint  off  = (jint)loff;
4058       _offset += negate ? -off : loff;
4059       NOT_PRODUCT(_tracer.offset_plus_k_3(n, _offset);)
4060       return true;
4061     }
4062     NOT_PRODUCT(_tracer.offset_plus_k_4(n);)
4063     return false;
4064   }
4065   if (_invar != NULL) { // already has an invariant
4066     NOT_PRODUCT(_tracer.offset_plus_k_5(n, _invar);)
4067     return false;
4068   }
4069 
4070   if (_analyze_only && is_loop_member(n)) {
4071     _nstack->push(n, _stack_idx++);
4072   }
4073   if (opc == Op_AddI) {
4074     if (n->in(2)->is_Con() && invariant(n->in(1))) {
4075       _negate_invar = negate;
4076       _invar = n->in(1);
4077       _offset += negate ? -(n->in(2)->get_int()) : n->in(2)->get_int();
4078       NOT_PRODUCT(_tracer.offset_plus_k_6(n, _invar, _negate_invar, _offset);)
4079       return true;
4080     } else if (n->in(1)->is_Con() && invariant(n->in(2))) {
4081       _offset += negate ? -(n->in(1)->get_int()) : n->in(1)->get_int();
4082       _negate_invar = negate;
4083       _invar = n->in(2);
4084       NOT_PRODUCT(_tracer.offset_plus_k_7(n, _invar, _negate_invar, _offset);)
4085       return true;
4086     }
4087   }
4088   if (opc == Op_SubI) {
4089     if (n->in(2)->is_Con() && invariant(n->in(1))) {
4090       _negate_invar = negate;
4091       _invar = n->in(1);
4092       _offset += !negate ? -(n->in(2)->get_int()) : n->in(2)->get_int();
4093       NOT_PRODUCT(_tracer.offset_plus_k_8(n, _invar, _negate_invar, _offset);)
4094       return true;
4095     } else if (n->in(1)->is_Con() && invariant(n->in(2))) {
4096       _offset += negate ? -(n->in(1)->get_int()) : n->in(1)->get_int();
4097       _negate_invar = !negate;
4098       _invar = n->in(2);
4099       NOT_PRODUCT(_tracer.offset_plus_k_9(n, _invar, _negate_invar, _offset);)
4100       return true;
4101     }
4102   }
4103 
4104   if (!is_loop_member(n)) {
4105     // 'n' is loop invariant. Skip ConvI2L and CastII nodes before checking if 'n' is dominating the pre loop.
4106     if (opc == Op_ConvI2L) {
4107       n = n->in(1);
4108     }
4109     if (n->Opcode() == Op_CastII) {
4110       // Skip CastII nodes
4111       assert(!is_loop_member(n), "sanity");
4112       n = n->in(1);
4113     }
4114     // Check if 'n' can really be used as invariant (not in main loop and dominating the pre loop).
4115     if (invariant(n)) {
4116       _negate_invar = negate;
4117       _invar = n;
4118       NOT_PRODUCT(_tracer.offset_plus_k_10(n, _invar, _negate_invar, _offset);)
4119       return true;
4120     }
4121   }
4122 
4123   NOT_PRODUCT(_tracer.offset_plus_k_11(n);)
4124   return false;
4125 }
4126 
4127 //-----------------has_potential_dependence-----------------
4128 // Check potential data dependence among all memory accesses.
4129 // We require every two accesses (with at least one store) of
4130 // the same element type has the same address expression.
4131 bool SWPointer::has_potential_dependence(GrowableArray<SWPointer*> swptrs) {
4132   for (int i1 = 0; i1 < swptrs.length(); i1++) {
4133     SWPointer* p1 = swptrs.at(i1);
4134     MemNode* n1 = p1->mem();
4135     BasicType bt1 = n1->memory_type();
4136 
4137     // Iterate over remaining SWPointers
4138     for (int i2 = i1 + 1; i2 < swptrs.length(); i2++) {
4139       SWPointer* p2 = swptrs.at(i2);
4140       MemNode* n2 = p2->mem();
4141       BasicType bt2 = n2->memory_type();
4142 
4143       // Data dependence exists between load-store, store-load
4144       // or store-store with the same element type or subword
4145       // size (subword load/store may have inaccurate type)
4146       if ((n1->is_Store() || n2->is_Store()) &&
4147           same_type_or_subword_size(bt1, bt2) && !p1->equal(*p2)) {
4148         return true;
4149       }
4150     }
4151   }
4152   return false;
4153 }
4154 
4155 //----------------------------print------------------------
4156 void SWPointer::print() {
4157 #ifndef PRODUCT
4158   tty->print("base: [%d]  adr: [%d]  scale: %d  offset: %d",
4159              _base != NULL ? _base->_idx : 0,
4160              _adr  != NULL ? _adr->_idx  : 0,
4161              _scale, _offset);
4162   if (_invar != NULL) {
4163     tty->print("  invar: %c[%d] << [%d]", _negate_invar?'-':'+', _invar->_idx, _invar_scale->_idx);
4164   }
4165   tty->cr();
4166 #endif
4167 }
4168 
4169 //----------------------------tracing------------------------
4170 #ifndef PRODUCT
4171 void SWPointer::Tracer::print_depth() const {
4172   for (int ii = 0; ii < _depth; ++ii) {
4173     tty->print("  ");
4174   }
4175 }
4176 
4177 void SWPointer::Tracer::ctor_1 (Node* mem) {
4178   if(_slp->is_trace_alignment()) {
4179     print_depth(); tty->print(" %d SWPointer::SWPointer: start alignment analysis", mem->_idx); mem->dump();
4180   }
4181 }
4182 
4183 void SWPointer::Tracer::ctor_2(Node* adr) {
4184   if(_slp->is_trace_alignment()) {
4185     //store_depth();
4186     inc_depth();
4187     print_depth(); tty->print(" %d (adr) SWPointer::SWPointer: ", adr->_idx); adr->dump();
4188     inc_depth();
4189     print_depth(); tty->print(" %d (base) SWPointer::SWPointer: ", adr->in(AddPNode::Base)->_idx); adr->in(AddPNode::Base)->dump();
4190   }
4191 }
4192 
4193 void SWPointer::Tracer::ctor_3(Node* adr, int i) {
4194   if(_slp->is_trace_alignment()) {
4195     inc_depth();
4196     Node* offset = adr->in(AddPNode::Offset);
4197     print_depth(); tty->print(" %d (offset) SWPointer::SWPointer: i = %d: ", offset->_idx, i); offset->dump();
4198   }
4199 }
4200 
4201 void SWPointer::Tracer::ctor_4(Node* adr, int i) {
4202   if(_slp->is_trace_alignment()) {
4203     inc_depth();
4204     print_depth(); tty->print(" %d (adr) SWPointer::SWPointer: i = %d: ", adr->_idx, i); adr->dump();
4205   }
4206 }
4207 
4208 void SWPointer::Tracer::ctor_5(Node* adr, Node* base, int i) {
4209   if(_slp->is_trace_alignment()) {
4210     inc_depth();
4211     if (base == adr) {
4212       print_depth(); tty->print_cr("  \\ %d (adr) == %d (base) SWPointer::SWPointer: breaking analysis at i = %d", adr->_idx, base->_idx, i);
4213     } else if (!adr->is_AddP()) {
4214       print_depth(); tty->print_cr("  \\ %d (adr) is NOT Addp SWPointer::SWPointer: breaking analysis at i = %d", adr->_idx, i);
4215     }
4216   }
4217 }
4218 
4219 void SWPointer::Tracer::ctor_6(Node* mem) {
4220   if(_slp->is_trace_alignment()) {
4221     //restore_depth();
4222     print_depth(); tty->print_cr(" %d (adr) SWPointer::SWPointer: stop analysis", mem->_idx);
4223   }
4224 }
4225 
4226 void SWPointer::Tracer::invariant_1(Node *n, Node *n_c) const {
4227   if (_slp->do_vector_loop() && _slp->is_debug() && _slp->_lpt->is_member(_slp->_phase->get_loop(n_c)) != (int)_slp->in_bb(n)) {
4228     int is_member =  _slp->_lpt->is_member(_slp->_phase->get_loop(n_c));
4229     int in_bb     =  _slp->in_bb(n);
4230     print_depth(); tty->print("  \\ ");  tty->print_cr(" %d SWPointer::invariant  conditions differ: n_c %d", n->_idx, n_c->_idx);
4231     print_depth(); tty->print("  \\ ");  tty->print_cr("is_member %d, in_bb %d", is_member, in_bb);
4232     print_depth(); tty->print("  \\ ");  n->dump();
4233     print_depth(); tty->print("  \\ ");  n_c->dump();
4234   }
4235 }
4236 
4237 void SWPointer::Tracer::scaled_iv_plus_offset_1(Node* n) {
4238   if(_slp->is_trace_alignment()) {
4239     print_depth(); tty->print(" %d SWPointer::scaled_iv_plus_offset testing node: ", n->_idx);
4240     n->dump();
4241   }
4242 }
4243 
4244 void SWPointer::Tracer::scaled_iv_plus_offset_2(Node* n) {
4245   if(_slp->is_trace_alignment()) {
4246     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: PASSED", n->_idx);
4247   }
4248 }
4249 
4250 void SWPointer::Tracer::scaled_iv_plus_offset_3(Node* n) {
4251   if(_slp->is_trace_alignment()) {
4252     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: PASSED", n->_idx);
4253   }
4254 }
4255 
4256 void SWPointer::Tracer::scaled_iv_plus_offset_4(Node* n) {
4257   if(_slp->is_trace_alignment()) {
4258     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: Op_AddI PASSED", n->_idx);
4259     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(1) is scaled_iv: ", n->in(1)->_idx); n->in(1)->dump();
4260     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(2) is offset_plus_k: ", n->in(2)->_idx); n->in(2)->dump();
4261   }
4262 }
4263 
4264 void SWPointer::Tracer::scaled_iv_plus_offset_5(Node* n) {
4265   if(_slp->is_trace_alignment()) {
4266     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: Op_AddI PASSED", n->_idx);
4267     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(2) is scaled_iv: ", n->in(2)->_idx); n->in(2)->dump();
4268     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(1) is offset_plus_k: ", n->in(1)->_idx); n->in(1)->dump();
4269   }
4270 }
4271 
4272 void SWPointer::Tracer::scaled_iv_plus_offset_6(Node* n) {
4273   if(_slp->is_trace_alignment()) {
4274     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: Op_SubI PASSED", n->_idx);
4275     print_depth(); tty->print("  \\  %d SWPointer::scaled_iv_plus_offset: in(1) is scaled_iv: ", n->in(1)->_idx); n->in(1)->dump();
4276     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(2) is offset_plus_k: ", n->in(2)->_idx); n->in(2)->dump();
4277   }
4278 }
4279 
4280 void SWPointer::Tracer::scaled_iv_plus_offset_7(Node* n) {
4281   if(_slp->is_trace_alignment()) {
4282     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: Op_SubI PASSED", n->_idx);
4283     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(2) is scaled_iv: ", n->in(2)->_idx); n->in(2)->dump();
4284     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv_plus_offset: in(1) is offset_plus_k: ", n->in(1)->_idx); n->in(1)->dump();
4285   }
4286 }
4287 
4288 void SWPointer::Tracer::scaled_iv_plus_offset_8(Node* n) {
4289   if(_slp->is_trace_alignment()) {
4290     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv_plus_offset: FAILED", n->_idx);
4291   }
4292 }
4293 
4294 void SWPointer::Tracer::scaled_iv_1(Node* n) {
4295   if(_slp->is_trace_alignment()) {
4296     print_depth(); tty->print(" %d SWPointer::scaled_iv: testing node: ", n->_idx); n->dump();
4297   }
4298 }
4299 
4300 void SWPointer::Tracer::scaled_iv_2(Node* n, int scale) {
4301   if(_slp->is_trace_alignment()) {
4302     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: FAILED since another _scale has been detected before", n->_idx);
4303     print_depth(); tty->print_cr("  \\ SWPointer::scaled_iv: _scale (%d) != 0", scale);
4304   }
4305 }
4306 
4307 void SWPointer::Tracer::scaled_iv_3(Node* n, int scale) {
4308   if(_slp->is_trace_alignment()) {
4309     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: is iv, setting _scale = %d", n->_idx, scale);
4310   }
4311 }
4312 
4313 void SWPointer::Tracer::scaled_iv_4(Node* n, int scale) {
4314   if(_slp->is_trace_alignment()) {
4315     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: Op_MulI PASSED, setting _scale = %d", n->_idx, scale);
4316     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(1) is iv: ", n->in(1)->_idx); n->in(1)->dump();
4317     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(2) is Con: ", n->in(2)->_idx); n->in(2)->dump();
4318   }
4319 }
4320 
4321 void SWPointer::Tracer::scaled_iv_5(Node* n, int scale) {
4322   if(_slp->is_trace_alignment()) {
4323     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: Op_MulI PASSED, setting _scale = %d", n->_idx, scale);
4324     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(2) is iv: ", n->in(2)->_idx); n->in(2)->dump();
4325     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(1) is Con: ", n->in(1)->_idx); n->in(1)->dump();
4326   }
4327 }
4328 
4329 void SWPointer::Tracer::scaled_iv_6(Node* n, int scale) {
4330   if(_slp->is_trace_alignment()) {
4331     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: Op_LShiftI PASSED, setting _scale = %d", n->_idx, scale);
4332     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(1) is iv: ", n->in(1)->_idx); n->in(1)->dump();
4333     print_depth(); tty->print("  \\ %d SWPointer::scaled_iv: in(2) is Con: ", n->in(2)->_idx); n->in(2)->dump();
4334   }
4335 }
4336 
4337 void SWPointer::Tracer::scaled_iv_7(Node* n) {
4338   if(_slp->is_trace_alignment()) {
4339     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: Op_ConvI2L PASSED", n->_idx);
4340     print_depth(); tty->print_cr("  \\ SWPointer::scaled_iv: in(1) %d is scaled_iv_plus_offset: ", n->in(1)->_idx);
4341     inc_depth(); inc_depth();
4342     print_depth(); n->in(1)->dump();
4343     dec_depth(); dec_depth();
4344   }
4345 }
4346 
4347 void SWPointer::Tracer::scaled_iv_8(Node* n, SWPointer* tmp) {
4348   if(_slp->is_trace_alignment()) {
4349     print_depth(); tty->print(" %d SWPointer::scaled_iv: Op_LShiftL, creating tmp SWPointer: ", n->_idx); tmp->print();
4350   }
4351 }
4352 
4353 void SWPointer::Tracer::scaled_iv_9(Node* n, int scale, int offset, Node* invar, bool negate_invar) {
4354   if(_slp->is_trace_alignment()) {
4355     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: Op_LShiftL PASSED, setting _scale = %d, _offset = %d", n->_idx, scale, offset);
4356     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",
4357     n->in(1)->_idx, n->in(2)->_idx, scale, offset);
4358     if (invar != NULL) {
4359       print_depth(); tty->print_cr("  \\ SWPointer::scaled_iv: scaled invariant: %c[%d]", (negate_invar?'-':'+'), invar->_idx);
4360     }
4361     inc_depth(); inc_depth();
4362     print_depth(); n->in(1)->dump();
4363     print_depth(); n->in(2)->dump();
4364     if (invar != NULL) {
4365       print_depth(); invar->dump();
4366     }
4367     dec_depth(); dec_depth();
4368   }
4369 }
4370 
4371 void SWPointer::Tracer::scaled_iv_10(Node* n) {
4372   if(_slp->is_trace_alignment()) {
4373     print_depth(); tty->print_cr(" %d SWPointer::scaled_iv: FAILED", n->_idx);
4374   }
4375 }
4376 
4377 void SWPointer::Tracer::offset_plus_k_1(Node* n) {
4378   if(_slp->is_trace_alignment()) {
4379     print_depth(); tty->print(" %d SWPointer::offset_plus_k: testing node: ", n->_idx); n->dump();
4380   }
4381 }
4382 
4383 void SWPointer::Tracer::offset_plus_k_2(Node* n, int _offset) {
4384   if(_slp->is_trace_alignment()) {
4385     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_ConI PASSED, setting _offset = %d", n->_idx, _offset);
4386   }
4387 }
4388 
4389 void SWPointer::Tracer::offset_plus_k_3(Node* n, int _offset) {
4390   if(_slp->is_trace_alignment()) {
4391     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_ConL PASSED, setting _offset = %d", n->_idx, _offset);
4392   }
4393 }
4394 
4395 void SWPointer::Tracer::offset_plus_k_4(Node* n) {
4396   if(_slp->is_trace_alignment()) {
4397     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: FAILED", n->_idx);
4398     print_depth(); tty->print_cr("  \\ " JLONG_FORMAT " SWPointer::offset_plus_k: Op_ConL FAILED, k is too big", n->get_long());
4399   }
4400 }
4401 
4402 void SWPointer::Tracer::offset_plus_k_5(Node* n, Node* _invar) {
4403   if(_slp->is_trace_alignment()) {
4404     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: FAILED since another invariant has been detected before", n->_idx);
4405     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: _invar != NULL: ", _invar->_idx); _invar->dump();
4406   }
4407 }
4408 
4409 void SWPointer::Tracer::offset_plus_k_6(Node* n, Node* _invar, bool _negate_invar, int _offset) {
4410   if(_slp->is_trace_alignment()) {
4411     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_AddI PASSED, setting _negate_invar = %d, _invar = %d, _offset = %d",
4412     n->_idx, _negate_invar, _invar->_idx, _offset);
4413     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(2) is Con: ", n->in(2)->_idx); n->in(2)->dump();
4414     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(1) is invariant: ", _invar->_idx); _invar->dump();
4415   }
4416 }
4417 
4418 void SWPointer::Tracer::offset_plus_k_7(Node* n, Node* _invar, bool _negate_invar, int _offset) {
4419   if(_slp->is_trace_alignment()) {
4420     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_AddI PASSED, setting _negate_invar = %d, _invar = %d, _offset = %d",
4421     n->_idx, _negate_invar, _invar->_idx, _offset);
4422     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(1) is Con: ", n->in(1)->_idx); n->in(1)->dump();
4423     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(2) is invariant: ", _invar->_idx); _invar->dump();
4424   }
4425 }
4426 
4427 void SWPointer::Tracer::offset_plus_k_8(Node* n, Node* _invar, bool _negate_invar, int _offset) {
4428   if(_slp->is_trace_alignment()) {
4429     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: Op_SubI is PASSED, setting _negate_invar = %d, _invar = %d, _offset = %d",
4430     n->_idx, _negate_invar, _invar->_idx, _offset);
4431     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(2) is Con: ", n->in(2)->_idx); n->in(2)->dump();
4432     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(1) is invariant: ", _invar->_idx); _invar->dump();
4433   }
4434 }
4435 
4436 void SWPointer::Tracer::offset_plus_k_9(Node* n, Node* _invar, bool _negate_invar, int _offset) {
4437   if(_slp->is_trace_alignment()) {
4438     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);
4439     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(1) is Con: ", n->in(1)->_idx); n->in(1)->dump();
4440     print_depth(); tty->print("  \\ %d SWPointer::offset_plus_k: in(2) is invariant: ", _invar->_idx); _invar->dump();
4441   }
4442 }
4443 
4444 void SWPointer::Tracer::offset_plus_k_10(Node* n, Node* _invar, bool _negate_invar, int _offset) {
4445   if(_slp->is_trace_alignment()) {
4446     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);
4447     print_depth(); tty->print_cr("  \\ %d SWPointer::offset_plus_k: is invariant", n->_idx);
4448   }
4449 }
4450 
4451 void SWPointer::Tracer::offset_plus_k_11(Node* n) {
4452   if(_slp->is_trace_alignment()) {
4453     print_depth(); tty->print_cr(" %d SWPointer::offset_plus_k: FAILED", n->_idx);
4454   }
4455 }
4456 
4457 #endif
4458 // ========================= OrderedPair =====================
4459 
4460 const OrderedPair OrderedPair::initial;
4461 
4462 // ========================= SWNodeInfo =====================
4463 
4464 const SWNodeInfo SWNodeInfo::initial;
4465 
4466 
4467 // ============================ DepGraph ===========================
4468 
4469 //------------------------------make_node---------------------------
4470 // Make a new dependence graph node for an ideal node.
4471 DepMem* DepGraph::make_node(Node* node) {
4472   DepMem* m = new (_arena) DepMem(node);
4473   if (node != NULL) {
4474     assert(_map.at_grow(node->_idx) == NULL, "one init only");
4475     _map.at_put_grow(node->_idx, m);
4476   }
4477   return m;
4478 }
4479 
4480 //------------------------------make_edge---------------------------
4481 // Make a new dependence graph edge from dpred -> dsucc
4482 DepEdge* DepGraph::make_edge(DepMem* dpred, DepMem* dsucc) {
4483   DepEdge* e = new (_arena) DepEdge(dpred, dsucc, dsucc->in_head(), dpred->out_head());
4484   dpred->set_out_head(e);
4485   dsucc->set_in_head(e);
4486   return e;
4487 }
4488 
4489 // ========================== DepMem ========================
4490 
4491 //------------------------------in_cnt---------------------------
4492 int DepMem::in_cnt() {
4493   int ct = 0;
4494   for (DepEdge* e = _in_head; e != NULL; e = e->next_in()) ct++;
4495   return ct;
4496 }
4497 
4498 //------------------------------out_cnt---------------------------
4499 int DepMem::out_cnt() {
4500   int ct = 0;
4501   for (DepEdge* e = _out_head; e != NULL; e = e->next_out()) ct++;
4502   return ct;
4503 }
4504 
4505 //------------------------------print-----------------------------
4506 void DepMem::print() {
4507 #ifndef PRODUCT
4508   tty->print("  DepNode %d (", _node->_idx);
4509   for (DepEdge* p = _in_head; p != NULL; p = p->next_in()) {
4510     Node* pred = p->pred()->node();
4511     tty->print(" %d", pred != NULL ? pred->_idx : 0);
4512   }
4513   tty->print(") [");
4514   for (DepEdge* s = _out_head; s != NULL; s = s->next_out()) {
4515     Node* succ = s->succ()->node();
4516     tty->print(" %d", succ != NULL ? succ->_idx : 0);
4517   }
4518   tty->print_cr(" ]");
4519 #endif
4520 }
4521 
4522 // =========================== DepEdge =========================
4523 
4524 //------------------------------DepPreds---------------------------
4525 void DepEdge::print() {
4526 #ifndef PRODUCT
4527   tty->print_cr("DepEdge: %d [ %d ]", _pred->node()->_idx, _succ->node()->_idx);
4528 #endif
4529 }
4530 
4531 // =========================== DepPreds =========================
4532 // Iterator over predecessor edges in the dependence graph.
4533 
4534 //------------------------------DepPreds---------------------------
4535 DepPreds::DepPreds(Node* n, DepGraph& dg) {
4536   _n = n;
4537   _done = false;
4538   if (_n->is_Store() || _n->is_Load()) {
4539     _next_idx = MemNode::Address;
4540     _end_idx  = n->req();
4541     _dep_next = dg.dep(_n)->in_head();
4542   } else if (_n->is_Mem()) {
4543     _next_idx = 0;
4544     _end_idx  = 0;
4545     _dep_next = dg.dep(_n)->in_head();
4546   } else {
4547     _next_idx = 1;
4548     _end_idx  = _n->req();
4549     _dep_next = NULL;
4550   }
4551   next();
4552 }
4553 
4554 //------------------------------next---------------------------
4555 void DepPreds::next() {
4556   if (_dep_next != NULL) {
4557     _current  = _dep_next->pred()->node();
4558     _dep_next = _dep_next->next_in();
4559   } else if (_next_idx < _end_idx) {
4560     _current  = _n->in(_next_idx++);
4561   } else {
4562     _done = true;
4563   }
4564 }
4565 
4566 // =========================== DepSuccs =========================
4567 // Iterator over successor edges in the dependence graph.
4568 
4569 //------------------------------DepSuccs---------------------------
4570 DepSuccs::DepSuccs(Node* n, DepGraph& dg) {
4571   _n = n;
4572   _done = false;
4573   if (_n->is_Load()) {
4574     _next_idx = 0;
4575     _end_idx  = _n->outcnt();
4576     _dep_next = dg.dep(_n)->out_head();
4577   } else if (_n->is_Mem() || (_n->is_Phi() && _n->bottom_type() == Type::MEMORY)) {
4578     _next_idx = 0;
4579     _end_idx  = 0;
4580     _dep_next = dg.dep(_n)->out_head();
4581   } else {
4582     _next_idx = 0;
4583     _end_idx  = _n->outcnt();
4584     _dep_next = NULL;
4585   }
4586   next();
4587 }
4588 
4589 //-------------------------------next---------------------------
4590 void DepSuccs::next() {
4591   if (_dep_next != NULL) {
4592     _current  = _dep_next->succ()->node();
4593     _dep_next = _dep_next->next_out();
4594   } else if (_next_idx < _end_idx) {
4595     _current  = _n->raw_out(_next_idx++);
4596   } else {
4597     _done = true;
4598   }
4599 }
4600 
4601 //
4602 // --------------------------------- vectorization/simd -----------------------------------
4603 //
4604 bool SuperWord::same_origin_idx(Node* a, Node* b) const {
4605   return a != NULL && b != NULL && _clone_map.same_idx(a->_idx, b->_idx);
4606 }
4607 bool SuperWord::same_generation(Node* a, Node* b) const {
4608   return a != NULL && b != NULL && _clone_map.same_gen(a->_idx, b->_idx);
4609 }
4610 
4611 Node*  SuperWord::find_phi_for_mem_dep(LoadNode* ld) {
4612   assert(in_bb(ld), "must be in block");
4613   if (_clone_map.gen(ld->_idx) == _ii_first) {
4614 #ifndef PRODUCT
4615     if (_vector_loop_debug) {
4616       tty->print_cr("SuperWord::find_phi_for_mem_dep _clone_map.gen(ld->_idx)=%d",
4617         _clone_map.gen(ld->_idx));
4618     }
4619 #endif
4620     return NULL; //we think that any ld in the first gen being vectorizable
4621   }
4622 
4623   Node* mem = ld->in(MemNode::Memory);
4624   if (mem->outcnt() <= 1) {
4625     // we don't want to remove the only edge from mem node to load
4626 #ifndef PRODUCT
4627     if (_vector_loop_debug) {
4628       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",
4629         mem->_idx, ld->_idx);
4630       ld->dump();
4631       mem->dump();
4632     }
4633 #endif
4634     return NULL;
4635   }
4636   if (!in_bb(mem) || same_generation(mem, ld)) {
4637 #ifndef PRODUCT
4638     if (_vector_loop_debug) {
4639       tty->print_cr("SuperWord::find_phi_for_mem_dep _clone_map.gen(mem->_idx)=%d",
4640         _clone_map.gen(mem->_idx));
4641     }
4642 #endif
4643     return NULL; // does not depend on loop volatile node or depends on the same generation
4644   }
4645 
4646   //otherwise first node should depend on mem-phi
4647   Node* first = first_node(ld);
4648   assert(first->is_Load(), "must be Load");
4649   Node* phi = first->as_Load()->in(MemNode::Memory);
4650   if (!phi->is_Phi() || phi->bottom_type() != Type::MEMORY) {
4651 #ifndef PRODUCT
4652     if (_vector_loop_debug) {
4653       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");
4654       ld->dump();
4655       first->dump();
4656     }
4657 #endif
4658     return NULL;
4659   }
4660 
4661   Node* tail = 0;
4662   for (int m = 0; m < _mem_slice_head.length(); m++) {
4663     if (_mem_slice_head.at(m) == phi) {
4664       tail = _mem_slice_tail.at(m);
4665     }
4666   }
4667   if (tail == 0) { //test that found phi is in the list  _mem_slice_head
4668 #ifndef PRODUCT
4669     if (_vector_loop_debug) {
4670       tty->print_cr("SuperWord::find_phi_for_mem_dep load %d is not vectorizable node, its phi %d is not _mem_slice_head",
4671         ld->_idx, phi->_idx);
4672       ld->dump();
4673       phi->dump();
4674     }
4675 #endif
4676     return NULL;
4677   }
4678 
4679   // now all conditions are met
4680   return phi;
4681 }
4682 
4683 Node* SuperWord::first_node(Node* nd) {
4684   for (int ii = 0; ii < _iteration_first.length(); ii++) {
4685     Node* nnn = _iteration_first.at(ii);
4686     if (same_origin_idx(nnn, nd)) {
4687 #ifndef PRODUCT
4688       if (_vector_loop_debug) {
4689         tty->print_cr("SuperWord::first_node: %d is the first iteration node for %d (_clone_map.idx(nnn->_idx) = %d)",
4690           nnn->_idx, nd->_idx, _clone_map.idx(nnn->_idx));
4691       }
4692 #endif
4693       return nnn;
4694     }
4695   }
4696 
4697 #ifndef PRODUCT
4698   if (_vector_loop_debug) {
4699     tty->print_cr("SuperWord::first_node: did not find first iteration node for %d (_clone_map.idx(nd->_idx)=%d)",
4700       nd->_idx, _clone_map.idx(nd->_idx));
4701   }
4702 #endif
4703   return 0;
4704 }
4705 
4706 Node* SuperWord::last_node(Node* nd) {
4707   for (int ii = 0; ii < _iteration_last.length(); ii++) {
4708     Node* nnn = _iteration_last.at(ii);
4709     if (same_origin_idx(nnn, nd)) {
4710 #ifndef PRODUCT
4711       if (_vector_loop_debug) {
4712         tty->print_cr("SuperWord::last_node _clone_map.idx(nnn->_idx)=%d, _clone_map.idx(nd->_idx)=%d",
4713           _clone_map.idx(nnn->_idx), _clone_map.idx(nd->_idx));
4714       }
4715 #endif
4716       return nnn;
4717     }
4718   }
4719   return 0;
4720 }
4721 
4722 int SuperWord::mark_generations() {
4723   Node *ii_err = NULL, *tail_err = NULL;
4724   for (int i = 0; i < _mem_slice_head.length(); i++) {
4725     Node* phi  = _mem_slice_head.at(i);
4726     assert(phi->is_Phi(), "must be phi");
4727 
4728     Node* tail = _mem_slice_tail.at(i);
4729     if (_ii_last == -1) {
4730       tail_err = tail;
4731       _ii_last = _clone_map.gen(tail->_idx);
4732     }
4733     else if (_ii_last != _clone_map.gen(tail->_idx)) {
4734 #ifndef PRODUCT
4735       if (TraceSuperWord && Verbose) {
4736         tty->print_cr("SuperWord::mark_generations _ii_last error - found different generations in two tail nodes ");
4737         tail->dump();
4738         tail_err->dump();
4739       }
4740 #endif
4741       return -1;
4742     }
4743 
4744     // find first iteration in the loop
4745     for (DUIterator_Fast imax, i = phi->fast_outs(imax); i < imax; i++) {
4746       Node* ii = phi->fast_out(i);
4747       if (in_bb(ii) && ii->is_Store()) { // we speculate that normally Stores of one and one only generation have deps from mem phi
4748         if (_ii_first == -1) {
4749           ii_err = ii;
4750           _ii_first = _clone_map.gen(ii->_idx);
4751         } else if (_ii_first != _clone_map.gen(ii->_idx)) {
4752 #ifndef PRODUCT
4753           if (TraceSuperWord && Verbose) {
4754             tty->print_cr("SuperWord::mark_generations: _ii_first was found before and not equal to one in this node (%d)", _ii_first);
4755             ii->dump();
4756             if (ii_err!= 0) {
4757               ii_err->dump();
4758             }
4759           }
4760 #endif
4761           return -1; // this phi has Stores from different generations of unroll and cannot be simd/vectorized
4762         }
4763       }
4764     }//for (DUIterator_Fast imax,
4765   }//for (int i...
4766 
4767   if (_ii_first == -1 || _ii_last == -1) {
4768     if (TraceSuperWord && Verbose) {
4769       tty->print_cr("SuperWord::mark_generations unknown error, something vent wrong");
4770     }
4771     return -1; // something vent wrong
4772   }
4773   // collect nodes in the first and last generations
4774   assert(_iteration_first.length() == 0, "_iteration_first must be empty");
4775   assert(_iteration_last.length() == 0, "_iteration_last must be empty");
4776   for (int j = 0; j < _block.length(); j++) {
4777     Node* n = _block.at(j);
4778     node_idx_t gen = _clone_map.gen(n->_idx);
4779     if ((signed)gen == _ii_first) {
4780       _iteration_first.push(n);
4781     } else if ((signed)gen == _ii_last) {
4782       _iteration_last.push(n);
4783     }
4784   }
4785 
4786   // building order of iterations
4787   if (_ii_order.length() == 0 && ii_err != 0) {
4788     assert(in_bb(ii_err) && ii_err->is_Store(), "should be Store in bb");
4789     Node* nd = ii_err;
4790     while(_clone_map.gen(nd->_idx) != _ii_last) {
4791       _ii_order.push(_clone_map.gen(nd->_idx));
4792       bool found = false;
4793       for (DUIterator_Fast imax, i = nd->fast_outs(imax); i < imax; i++) {
4794         Node* use = nd->fast_out(i);
4795         if (same_origin_idx(use, nd) && use->as_Store()->in(MemNode::Memory) == nd) {
4796           found = true;
4797           nd = use;
4798           break;
4799         }
4800       }//for
4801 
4802       if (found == false) {
4803         if (TraceSuperWord && Verbose) {
4804           tty->print_cr("SuperWord::mark_generations: Cannot build order of iterations - no dependent Store for %d", nd->_idx);
4805         }
4806         _ii_order.clear();
4807         return -1;
4808       }
4809     } //while
4810     _ii_order.push(_clone_map.gen(nd->_idx));
4811   }
4812 
4813 #ifndef PRODUCT
4814   if (_vector_loop_debug) {
4815     tty->print_cr("SuperWord::mark_generations");
4816     tty->print_cr("First generation (%d) nodes:", _ii_first);
4817     for (int ii = 0; ii < _iteration_first.length(); ii++)  _iteration_first.at(ii)->dump();
4818     tty->print_cr("Last generation (%d) nodes:", _ii_last);
4819     for (int ii = 0; ii < _iteration_last.length(); ii++)  _iteration_last.at(ii)->dump();
4820     tty->print_cr(" ");
4821 
4822     tty->print("SuperWord::List of generations: ");
4823     for (int jj = 0; jj < _ii_order.length(); ++jj) {
4824       tty->print("%d:%d ", jj, _ii_order.at(jj));
4825     }
4826     tty->print_cr(" ");
4827   }
4828 #endif
4829 
4830   return _ii_first;
4831 }
4832 
4833 bool SuperWord::fix_commutative_inputs(Node* gold, Node* fix) {
4834   assert(gold->is_Add() && fix->is_Add() || gold->is_Mul() && fix->is_Mul(), "should be only Add or Mul nodes");
4835   assert(same_origin_idx(gold, fix), "should be clones of the same node");
4836   Node* gin1 = gold->in(1);
4837   Node* gin2 = gold->in(2);
4838   Node* fin1 = fix->in(1);
4839   Node* fin2 = fix->in(2);
4840   bool swapped = false;
4841 
4842   if (in_bb(gin1) && in_bb(gin2) && in_bb(fin1) && in_bb(fin2)) {
4843     if (same_origin_idx(gin1, fin1) &&
4844         same_origin_idx(gin2, fin2)) {
4845       return true; // nothing to fix
4846     }
4847     if (same_origin_idx(gin1, fin2) &&
4848         same_origin_idx(gin2, fin1)) {
4849       fix->swap_edges(1, 2);
4850       swapped = true;
4851     }
4852   }
4853   // at least one input comes from outside of bb
4854   if (gin1->_idx == fin1->_idx)  {
4855     return true; // nothing to fix
4856   }
4857   if (!swapped && (gin1->_idx == fin2->_idx || gin2->_idx == fin1->_idx))  { //swapping is expensive, check condition first
4858     fix->swap_edges(1, 2);
4859     swapped = true;
4860   }
4861 
4862   if (swapped) {
4863 #ifndef PRODUCT
4864     if (_vector_loop_debug) {
4865       tty->print_cr("SuperWord::fix_commutative_inputs: fixed node %d", fix->_idx);
4866     }
4867 #endif
4868     return true;
4869   }
4870 
4871   if (TraceSuperWord && Verbose) {
4872     tty->print_cr("SuperWord::fix_commutative_inputs: cannot fix node %d", fix->_idx);
4873   }
4874 
4875   return false;
4876 }
4877 
4878 bool SuperWord::pack_parallel() {
4879 #ifndef PRODUCT
4880   if (_vector_loop_debug) {
4881     tty->print_cr("SuperWord::pack_parallel: START");
4882   }
4883 #endif
4884 
4885   _packset.clear();
4886 
4887   if (_ii_order.is_empty()) {
4888 #ifndef PRODUCT
4889     if (_vector_loop_debug) {
4890       tty->print_cr("SuperWord::pack_parallel: EMPTY");
4891     }
4892 #endif
4893     return false;
4894   }
4895 
4896   for (int ii = 0; ii < _iteration_first.length(); ii++) {
4897     Node* nd = _iteration_first.at(ii);
4898     if (in_bb(nd) && (nd->is_Load() || nd->is_Store() || nd->is_Add() || nd->is_Mul())) {
4899       Node_List* pk = new Node_List();
4900       pk->push(nd);
4901       for (int gen = 1; gen < _ii_order.length(); ++gen) {
4902         for (int kk = 0; kk < _block.length(); kk++) {
4903           Node* clone = _block.at(kk);
4904           if (same_origin_idx(clone, nd) &&
4905               _clone_map.gen(clone->_idx) == _ii_order.at(gen)) {
4906             if (nd->is_Add() || nd->is_Mul()) {
4907               fix_commutative_inputs(nd, clone);
4908             }
4909             pk->push(clone);
4910             if (pk->size() == 4) {
4911               _packset.append(pk);
4912 #ifndef PRODUCT
4913               if (_vector_loop_debug) {
4914                 tty->print_cr("SuperWord::pack_parallel: added pack ");
4915                 pk->dump();
4916               }
4917 #endif
4918               if (_clone_map.gen(clone->_idx) != _ii_last) {
4919                 pk = new Node_List();
4920               }
4921             }
4922             break;
4923           }
4924         }
4925       }//for
4926     }//if
4927   }//for
4928 
4929 #ifndef PRODUCT
4930   if (_vector_loop_debug) {
4931     tty->print_cr("SuperWord::pack_parallel: END");
4932   }
4933 #endif
4934 
4935   return true;
4936 }
4937 
4938 bool SuperWord::hoist_loads_in_graph() {
4939   GrowableArray<Node*> loads;
4940 
4941 #ifndef PRODUCT
4942   if (_vector_loop_debug) {
4943     tty->print_cr("SuperWord::hoist_loads_in_graph: total number _mem_slice_head.length() = %d", _mem_slice_head.length());
4944   }
4945 #endif
4946 
4947   for (int i = 0; i < _mem_slice_head.length(); i++) {
4948     Node* n = _mem_slice_head.at(i);
4949     if ( !in_bb(n) || !n->is_Phi() || n->bottom_type() != Type::MEMORY) {
4950       if (TraceSuperWord && Verbose) {
4951         tty->print_cr("SuperWord::hoist_loads_in_graph: skipping unexpected node n=%d", n->_idx);
4952       }
4953       continue;
4954     }
4955 
4956 #ifndef PRODUCT
4957     if (_vector_loop_debug) {
4958       tty->print_cr("SuperWord::hoist_loads_in_graph: processing phi %d  = _mem_slice_head.at(%d);", n->_idx, i);
4959     }
4960 #endif
4961 
4962     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4963       Node* ld = n->fast_out(i);
4964       if (ld->is_Load() && ld->as_Load()->in(MemNode::Memory) == n && in_bb(ld)) {
4965         for (int i = 0; i < _block.length(); i++) {
4966           Node* ld2 = _block.at(i);
4967           if (ld2->is_Load() && same_origin_idx(ld, ld2) &&
4968               !same_generation(ld, ld2)) { // <= do not collect the first generation ld
4969 #ifndef PRODUCT
4970             if (_vector_loop_debug) {
4971               tty->print_cr("SuperWord::hoist_loads_in_graph: will try to hoist load ld2->_idx=%d, cloned from %d (ld->_idx=%d)",
4972                 ld2->_idx, _clone_map.idx(ld->_idx), ld->_idx);
4973             }
4974 #endif
4975             // could not do on-the-fly, since iterator is immutable
4976             loads.push(ld2);
4977           }
4978         }// for
4979       }//if
4980     }//for (DUIterator_Fast imax,
4981   }//for (int i = 0; i
4982 
4983   for (int i = 0; i < loads.length(); i++) {
4984     LoadNode* ld = loads.at(i)->as_Load();
4985     Node* phi = find_phi_for_mem_dep(ld);
4986     if (phi != NULL) {
4987 #ifndef PRODUCT
4988       if (_vector_loop_debug) {
4989         tty->print_cr("SuperWord::hoist_loads_in_graph replacing MemNode::Memory(%d) edge in %d with one from %d",
4990           MemNode::Memory, ld->_idx, phi->_idx);
4991       }
4992 #endif
4993       _igvn.replace_input_of(ld, MemNode::Memory, phi);
4994     }
4995   }//for
4996 
4997   restart(); // invalidate all basic structures, since we rebuilt the graph
4998 
4999   if (TraceSuperWord && Verbose) {
5000     tty->print_cr("\nSuperWord::hoist_loads_in_graph() the graph was rebuilt, all structures invalidated and need rebuild");
5001   }
5002 
5003   return true;
5004 }
--- EOF ---