1 /*
   2  * Copyright (c) 1998, 2018, 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 
  25 // output_c.cpp - Class CPP file output routines for architecture definition
  26 
  27 #include "adlc.hpp"
  28 
  29 // Utilities to characterize effect statements
  30 static bool is_def(int usedef) {
  31   switch(usedef) {
  32   case Component::DEF:
  33   case Component::USE_DEF: return true; break;
  34   }
  35   return false;
  36 }
  37 
  38 static bool is_use(int usedef) {
  39   switch(usedef) {
  40   case Component::USE:
  41   case Component::USE_DEF:
  42   case Component::USE_KILL: return true; break;
  43   }
  44   return false;
  45 }
  46 
  47 static bool is_kill(int usedef) {
  48   switch(usedef) {
  49   case Component::KILL:
  50   case Component::USE_KILL: return true; break;
  51   }
  52   return false;
  53 }
  54 
  55 // Define  an array containing the machine register names, strings.
  56 static void defineRegNames(FILE *fp, RegisterForm *registers) {
  57   if (registers) {
  58     fprintf(fp,"\n");
  59     fprintf(fp,"// An array of character pointers to machine register names.\n");
  60     fprintf(fp,"const char *Matcher::regName[REG_COUNT] = {\n");
  61 
  62     // Output the register name for each register in the allocation classes
  63     RegDef *reg_def = NULL;
  64     RegDef *next = NULL;
  65     registers->reset_RegDefs();
  66     for (reg_def = registers->iter_RegDefs(); reg_def != NULL; reg_def = next) {
  67       next = registers->iter_RegDefs();
  68       const char *comma = (next != NULL) ? "," : " // no trailing comma";
  69       fprintf(fp,"  \"%s\"%s\n", reg_def->_regname, comma);
  70     }
  71 
  72     // Finish defining enumeration
  73     fprintf(fp,"};\n");
  74 
  75     fprintf(fp,"\n");
  76     fprintf(fp,"// An array of character pointers to machine register names.\n");
  77     fprintf(fp,"const VMReg OptoReg::opto2vm[REG_COUNT] = {\n");
  78     reg_def = NULL;
  79     next = NULL;
  80     registers->reset_RegDefs();
  81     for (reg_def = registers->iter_RegDefs(); reg_def != NULL; reg_def = next) {
  82       next = registers->iter_RegDefs();
  83       const char *comma = (next != NULL) ? "," : " // no trailing comma";
  84       fprintf(fp,"\t%s%s\n", reg_def->_concrete, comma);
  85     }
  86     // Finish defining array
  87     fprintf(fp,"\t};\n");
  88     fprintf(fp,"\n");
  89 
  90     fprintf(fp," OptoReg::Name OptoReg::vm2opto[ConcreteRegisterImpl::number_of_registers];\n");
  91 
  92   }
  93 }
  94 
  95 // Define an array containing the machine register encoding values
  96 static void defineRegEncodes(FILE *fp, RegisterForm *registers) {
  97   if (registers) {
  98     fprintf(fp,"\n");
  99     fprintf(fp,"// An array of the machine register encode values\n");
 100     fprintf(fp,"const unsigned char Matcher::_regEncode[REG_COUNT] = {\n");
 101 
 102     // Output the register encoding for each register in the allocation classes
 103     RegDef *reg_def = NULL;
 104     RegDef *next    = NULL;
 105     registers->reset_RegDefs();
 106     for (reg_def = registers->iter_RegDefs(); reg_def != NULL; reg_def = next) {
 107       next = registers->iter_RegDefs();
 108       const char* register_encode = reg_def->register_encode();
 109       const char *comma = (next != NULL) ? "," : " // no trailing comma";
 110       int encval;
 111       if (!ADLParser::is_int_token(register_encode, encval)) {
 112         fprintf(fp,"  %s%s  // %s\n", register_encode, comma, reg_def->_regname);
 113       } else {
 114         // Output known constants in hex char format (backward compatibility).
 115         assert(encval < 256, "Exceeded supported width for register encoding");
 116         fprintf(fp,"  (unsigned char)'\\x%X'%s  // %s\n", encval, comma, reg_def->_regname);
 117       }
 118     }
 119     // Finish defining enumeration
 120     fprintf(fp,"};\n");
 121 
 122   } // Done defining array
 123 }
 124 
 125 // Output an enumeration of register class names
 126 static void defineRegClassEnum(FILE *fp, RegisterForm *registers) {
 127   if (registers) {
 128     // Output an enumeration of register class names
 129     fprintf(fp,"\n");
 130     fprintf(fp,"// Enumeration of register class names\n");
 131     fprintf(fp, "enum machRegisterClass {\n");
 132     registers->_rclasses.reset();
 133     for (const char *class_name = NULL; (class_name = registers->_rclasses.iter()) != NULL;) {
 134       const char * class_name_to_upper = toUpper(class_name);
 135       fprintf(fp,"  %s,\n", class_name_to_upper);
 136       delete[] class_name_to_upper;
 137     }
 138     // Finish defining enumeration
 139     fprintf(fp, "  _last_Mach_Reg_Class\n");
 140     fprintf(fp, "};\n");
 141   }
 142 }
 143 
 144 // Declare an enumeration of user-defined register classes
 145 // and a list of register masks, one for each class.
 146 void ArchDesc::declare_register_masks(FILE *fp_hpp) {
 147   const char  *rc_name;
 148 
 149   if (_register) {
 150     // Build enumeration of user-defined register classes.
 151     defineRegClassEnum(fp_hpp, _register);
 152 
 153     // Generate a list of register masks, one for each class.
 154     fprintf(fp_hpp,"\n");
 155     fprintf(fp_hpp,"// Register masks, one for each register class.\n");
 156     _register->_rclasses.reset();
 157     for (rc_name = NULL; (rc_name = _register->_rclasses.iter()) != NULL;) {
 158       RegClass *reg_class = _register->getRegClass(rc_name);
 159       assert(reg_class, "Using an undefined register class");
 160       reg_class->declare_register_masks(fp_hpp);
 161     }
 162   }
 163 }
 164 
 165 // Generate an enumeration of user-defined register classes
 166 // and a list of register masks, one for each class.
 167 void ArchDesc::build_register_masks(FILE *fp_cpp) {
 168   const char  *rc_name;
 169 
 170   if (_register) {
 171     // Generate a list of register masks, one for each class.
 172     fprintf(fp_cpp,"\n");
 173     fprintf(fp_cpp,"// Register masks, one for each register class.\n");
 174     _register->_rclasses.reset();
 175     for (rc_name = NULL; (rc_name = _register->_rclasses.iter()) != NULL;) {
 176       RegClass *reg_class = _register->getRegClass(rc_name);
 177       assert(reg_class, "Using an undefined register class");
 178       reg_class->build_register_masks(fp_cpp);
 179     }
 180   }
 181 }
 182 
 183 // Compute an index for an array in the pipeline_reads_NNN arrays
 184 static int pipeline_reads_initializer(FILE *fp_cpp, NameList &pipeline_reads, PipeClassForm *pipeclass)
 185 {
 186   int templen = 1;
 187   int paramcount = 0;
 188   const char *paramname;
 189 
 190   if (pipeclass->_parameters.count() == 0)
 191     return -1;
 192 
 193   pipeclass->_parameters.reset();
 194   paramname = pipeclass->_parameters.iter();
 195   const PipeClassOperandForm *pipeopnd =
 196     (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];
 197   if (pipeopnd && !pipeopnd->isWrite() && strcmp(pipeopnd->_stage, "Universal"))
 198     pipeclass->_parameters.reset();
 199 
 200   while ( (paramname = pipeclass->_parameters.iter()) != NULL ) {
 201     const PipeClassOperandForm *tmppipeopnd =
 202         (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];
 203 
 204     if (tmppipeopnd)
 205       templen += 10 + (int)strlen(tmppipeopnd->_stage);
 206     else
 207       templen += 19;
 208 
 209     paramcount++;
 210   }
 211 
 212   // See if the count is zero
 213   if (paramcount == 0) {
 214     return -1;
 215   }
 216 
 217   char *operand_stages = new char [templen];
 218   operand_stages[0] = 0;
 219   int i = 0;
 220   templen = 0;
 221 
 222   pipeclass->_parameters.reset();
 223   paramname = pipeclass->_parameters.iter();
 224   pipeopnd = (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];
 225   if (pipeopnd && !pipeopnd->isWrite() && strcmp(pipeopnd->_stage, "Universal"))
 226     pipeclass->_parameters.reset();
 227 
 228   while ( (paramname = pipeclass->_parameters.iter()) != NULL ) {
 229     const PipeClassOperandForm *tmppipeopnd =
 230         (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];
 231     templen += sprintf(&operand_stages[templen], "  stage_%s%c\n",
 232       tmppipeopnd ? tmppipeopnd->_stage : "undefined",
 233       (++i < paramcount ? ',' : ' ') );
 234   }
 235 
 236   // See if the same string is in the table
 237   int ndx = pipeline_reads.index(operand_stages);
 238 
 239   // No, add it to the table
 240   if (ndx < 0) {
 241     pipeline_reads.addName(operand_stages);
 242     ndx = pipeline_reads.index(operand_stages);
 243 
 244     fprintf(fp_cpp, "static const enum machPipelineStages pipeline_reads_%03d[%d] = {\n%s};\n\n",
 245       ndx+1, paramcount, operand_stages);
 246   }
 247   else
 248     delete [] operand_stages;
 249 
 250   return (ndx);
 251 }
 252 
 253 // Compute an index for an array in the pipeline_res_stages_NNN arrays
 254 static int pipeline_res_stages_initializer(
 255   FILE *fp_cpp,
 256   PipelineForm *pipeline,
 257   NameList &pipeline_res_stages,
 258   PipeClassForm *pipeclass)
 259 {
 260   const PipeClassResourceForm *piperesource;
 261   int * res_stages = new int [pipeline->_rescount];
 262   int i;
 263 
 264   for (i = 0; i < pipeline->_rescount; i++)
 265      res_stages[i] = 0;
 266 
 267   for (pipeclass->_resUsage.reset();
 268        (piperesource = (const PipeClassResourceForm *)pipeclass->_resUsage.iter()) != NULL; ) {
 269     int used_mask = pipeline->_resdict[piperesource->_resource]->is_resource()->mask();
 270     for (i = 0; i < pipeline->_rescount; i++)
 271       if ((1 << i) & used_mask) {
 272         int stage = pipeline->_stages.index(piperesource->_stage);
 273         if (res_stages[i] < stage+1)
 274           res_stages[i] = stage+1;
 275       }
 276   }
 277 
 278   // Compute the length needed for the resource list
 279   int commentlen = 0;
 280   int max_stage = 0;
 281   for (i = 0; i < pipeline->_rescount; i++) {
 282     if (res_stages[i] == 0) {
 283       if (max_stage < 9)
 284         max_stage = 9;
 285     }
 286     else {
 287       int stagelen = (int)strlen(pipeline->_stages.name(res_stages[i]-1));
 288       if (max_stage < stagelen)
 289         max_stage = stagelen;
 290     }
 291 
 292     commentlen += (int)strlen(pipeline->_reslist.name(i));
 293   }
 294 
 295   int templen = 1 + commentlen + pipeline->_rescount * (max_stage + 14);
 296 
 297   // Allocate space for the resource list
 298   char * resource_stages = new char [templen];
 299 
 300   templen = 0;
 301   for (i = 0; i < pipeline->_rescount; i++) {
 302     const char * const resname =
 303       res_stages[i] == 0 ? "undefined" : pipeline->_stages.name(res_stages[i]-1);
 304 
 305     templen += sprintf(&resource_stages[templen], "  stage_%s%-*s // %s\n",
 306       resname, max_stage - (int)strlen(resname) + 1,
 307       (i < pipeline->_rescount-1) ? "," : "",
 308       pipeline->_reslist.name(i));
 309   }
 310 
 311   // See if the same string is in the table
 312   int ndx = pipeline_res_stages.index(resource_stages);
 313 
 314   // No, add it to the table
 315   if (ndx < 0) {
 316     pipeline_res_stages.addName(resource_stages);
 317     ndx = pipeline_res_stages.index(resource_stages);
 318 
 319     fprintf(fp_cpp, "static const enum machPipelineStages pipeline_res_stages_%03d[%d] = {\n%s};\n\n",
 320       ndx+1, pipeline->_rescount, resource_stages);
 321   }
 322   else
 323     delete [] resource_stages;
 324 
 325   delete [] res_stages;
 326 
 327   return (ndx);
 328 }
 329 
 330 // Compute an index for an array in the pipeline_res_cycles_NNN arrays
 331 static int pipeline_res_cycles_initializer(
 332   FILE *fp_cpp,
 333   PipelineForm *pipeline,
 334   NameList &pipeline_res_cycles,
 335   PipeClassForm *pipeclass)
 336 {
 337   const PipeClassResourceForm *piperesource;
 338   int * res_cycles = new int [pipeline->_rescount];
 339   int i;
 340 
 341   for (i = 0; i < pipeline->_rescount; i++)
 342      res_cycles[i] = 0;
 343 
 344   for (pipeclass->_resUsage.reset();
 345        (piperesource = (const PipeClassResourceForm *)pipeclass->_resUsage.iter()) != NULL; ) {
 346     int used_mask = pipeline->_resdict[piperesource->_resource]->is_resource()->mask();
 347     for (i = 0; i < pipeline->_rescount; i++)
 348       if ((1 << i) & used_mask) {
 349         int cycles = piperesource->_cycles;
 350         if (res_cycles[i] < cycles)
 351           res_cycles[i] = cycles;
 352       }
 353   }
 354 
 355   // Pre-compute the string length
 356   int templen;
 357   int cyclelen = 0, commentlen = 0;
 358   int max_cycles = 0;
 359   char temp[32];
 360 
 361   for (i = 0; i < pipeline->_rescount; i++) {
 362     if (max_cycles < res_cycles[i])
 363       max_cycles = res_cycles[i];
 364     templen = sprintf(temp, "%d", res_cycles[i]);
 365     if (cyclelen < templen)
 366       cyclelen = templen;
 367     commentlen += (int)strlen(pipeline->_reslist.name(i));
 368   }
 369 
 370   templen = 1 + commentlen + (cyclelen + 8) * pipeline->_rescount;
 371 
 372   // Allocate space for the resource list
 373   char * resource_cycles = new char [templen];
 374 
 375   templen = 0;
 376 
 377   for (i = 0; i < pipeline->_rescount; i++) {
 378     templen += sprintf(&resource_cycles[templen], "  %*d%c // %s\n",
 379       cyclelen, res_cycles[i], (i < pipeline->_rescount-1) ? ',' : ' ', pipeline->_reslist.name(i));
 380   }
 381 
 382   // See if the same string is in the table
 383   int ndx = pipeline_res_cycles.index(resource_cycles);
 384 
 385   // No, add it to the table
 386   if (ndx < 0) {
 387     pipeline_res_cycles.addName(resource_cycles);
 388     ndx = pipeline_res_cycles.index(resource_cycles);
 389 
 390     fprintf(fp_cpp, "static const uint pipeline_res_cycles_%03d[%d] = {\n%s};\n\n",
 391       ndx+1, pipeline->_rescount, resource_cycles);
 392   }
 393   else
 394     delete [] resource_cycles;
 395 
 396   delete [] res_cycles;
 397 
 398   return (ndx);
 399 }
 400 
 401 //typedef unsigned long long uint64_t;
 402 
 403 // Compute an index for an array in the pipeline_res_mask_NNN arrays
 404 static int pipeline_res_mask_initializer(
 405   FILE *fp_cpp,
 406   PipelineForm *pipeline,
 407   NameList &pipeline_res_mask,
 408   NameList &pipeline_res_args,
 409   PipeClassForm *pipeclass)
 410 {
 411   const PipeClassResourceForm *piperesource;
 412   const uint rescount      = pipeline->_rescount;
 413   const uint maxcycleused  = pipeline->_maxcycleused;
 414   const uint cyclemasksize = (maxcycleused + 31) >> 5;
 415 
 416   int i, j;
 417   int element_count = 0;
 418   uint *res_mask = new uint [cyclemasksize];
 419   uint resources_used             = 0;
 420   uint resources_used_exclusively = 0;
 421 
 422   for (pipeclass->_resUsage.reset();
 423        (piperesource = (const PipeClassResourceForm*)pipeclass->_resUsage.iter()) != NULL; ) {
 424     element_count++;
 425   }
 426 
 427   // Pre-compute the string length
 428   int templen;
 429   int commentlen = 0;
 430   int max_cycles = 0;
 431 
 432   int cyclelen = ((maxcycleused + 3) >> 2);
 433   int masklen = (rescount + 3) >> 2;
 434 
 435   int cycledigit = 0;
 436   for (i = maxcycleused; i > 0; i /= 10)
 437     cycledigit++;
 438 
 439   int maskdigit = 0;
 440   for (i = rescount; i > 0; i /= 10)
 441     maskdigit++;
 442 
 443   static const char* pipeline_use_cycle_mask = "Pipeline_Use_Cycle_Mask";
 444   static const char* pipeline_use_element    = "Pipeline_Use_Element";
 445 
 446   templen = 1 +
 447     (int)(strlen(pipeline_use_cycle_mask) + (int)strlen(pipeline_use_element) +
 448      (cyclemasksize * 12) + masklen + (cycledigit * 2) + 30) * element_count;
 449 
 450   // Allocate space for the resource list
 451   char * resource_mask = new char [templen];
 452   char * last_comma = NULL;
 453 
 454   templen = 0;
 455 
 456   for (pipeclass->_resUsage.reset();
 457        (piperesource = (const PipeClassResourceForm*)pipeclass->_resUsage.iter()) != NULL; ) {
 458     int used_mask = pipeline->_resdict[piperesource->_resource]->is_resource()->mask();
 459 
 460     if (!used_mask) {
 461       fprintf(stderr, "*** used_mask is 0 ***\n");
 462     }
 463 
 464     resources_used |= used_mask;
 465 
 466     uint lb, ub;
 467 
 468     for (lb =  0; (used_mask & (1 << lb)) == 0; lb++);
 469     for (ub = 31; (used_mask & (1 << ub)) == 0; ub--);
 470 
 471     if (lb == ub) {
 472       resources_used_exclusively |= used_mask;
 473     }
 474 
 475     int formatlen =
 476       sprintf(&resource_mask[templen], "  %s(0x%0*x, %*d, %*d, %s %s(",
 477         pipeline_use_element,
 478         masklen, used_mask,
 479         cycledigit, lb, cycledigit, ub,
 480         ((used_mask & (used_mask-1)) != 0) ? "true, " : "false,",
 481         pipeline_use_cycle_mask);
 482 
 483     templen += formatlen;
 484 
 485     memset(res_mask, 0, cyclemasksize * sizeof(uint));
 486 
 487     int cycles = piperesource->_cycles;
 488     uint stage          = pipeline->_stages.index(piperesource->_stage);
 489     if ((uint)NameList::Not_in_list == stage) {
 490       fprintf(stderr,
 491               "pipeline_res_mask_initializer: "
 492               "semantic error: "
 493               "pipeline stage undeclared: %s\n",
 494               piperesource->_stage);
 495       exit(1);
 496     }
 497     uint upper_limit    = stage + cycles - 1;
 498     uint lower_limit    = stage - 1;
 499     uint upper_idx      = upper_limit >> 5;
 500     uint lower_idx      = lower_limit >> 5;
 501     uint upper_position = upper_limit & 0x1f;
 502     uint lower_position = lower_limit & 0x1f;
 503 
 504     uint mask = (((uint)1) << upper_position) - 1;
 505 
 506     while (upper_idx > lower_idx) {
 507       res_mask[upper_idx--] |= mask;
 508       mask = (uint)-1;
 509     }
 510 
 511     mask -= (((uint)1) << lower_position) - 1;
 512     res_mask[upper_idx] |= mask;
 513 
 514     for (j = cyclemasksize-1; j >= 0; j--) {
 515       formatlen =
 516         sprintf(&resource_mask[templen], "0x%08x%s", res_mask[j], j > 0 ? ", " : "");
 517       templen += formatlen;
 518     }
 519 
 520     resource_mask[templen++] = ')';
 521     resource_mask[templen++] = ')';
 522     last_comma = &resource_mask[templen];
 523     resource_mask[templen++] = ',';
 524     resource_mask[templen++] = '\n';
 525   }
 526 
 527   resource_mask[templen] = 0;
 528   if (last_comma) {
 529     last_comma[0] = ' ';
 530   }
 531 
 532   // See if the same string is in the table
 533   int ndx = pipeline_res_mask.index(resource_mask);
 534 
 535   // No, add it to the table
 536   if (ndx < 0) {
 537     pipeline_res_mask.addName(resource_mask);
 538     ndx = pipeline_res_mask.index(resource_mask);
 539 
 540     if (strlen(resource_mask) > 0)
 541       fprintf(fp_cpp, "static const Pipeline_Use_Element pipeline_res_mask_%03d[%d] = {\n%s};\n\n",
 542         ndx+1, element_count, resource_mask);
 543 
 544     char* args = new char [9 + 2*masklen + maskdigit];
 545 
 546     sprintf(args, "0x%0*x, 0x%0*x, %*d",
 547       masklen, resources_used,
 548       masklen, resources_used_exclusively,
 549       maskdigit, element_count);
 550 
 551     pipeline_res_args.addName(args);
 552   }
 553   else {
 554     delete [] resource_mask;
 555   }
 556 
 557   delete [] res_mask;
 558 //delete [] res_masks;
 559 
 560   return (ndx);
 561 }
 562 
 563 void ArchDesc::build_pipe_classes(FILE *fp_cpp) {
 564   const char *classname;
 565   const char *resourcename;
 566   int resourcenamelen = 0;
 567   NameList pipeline_reads;
 568   NameList pipeline_res_stages;
 569   NameList pipeline_res_cycles;
 570   NameList pipeline_res_masks;
 571   NameList pipeline_res_args;
 572   const int default_latency = 1;
 573   const int non_operand_latency = 0;
 574   const int node_latency = 0;
 575 
 576   if (!_pipeline) {
 577     fprintf(fp_cpp, "uint Node::latency(uint i) const {\n");
 578     fprintf(fp_cpp, "  // assert(false, \"pipeline functionality is not defined\");\n");
 579     fprintf(fp_cpp, "  return %d;\n", non_operand_latency);
 580     fprintf(fp_cpp, "}\n");
 581     return;
 582   }
 583 
 584   fprintf(fp_cpp, "\n");
 585   fprintf(fp_cpp, "//------------------Pipeline Methods-----------------------------------------\n");
 586   fprintf(fp_cpp, "#ifndef PRODUCT\n");
 587   fprintf(fp_cpp, "const char * Pipeline::stageName(uint s) {\n");
 588   fprintf(fp_cpp, "  static const char * const _stage_names[] = {\n");
 589   fprintf(fp_cpp, "    \"undefined\"");
 590 
 591   for (int s = 0; s < _pipeline->_stagecnt; s++)
 592     fprintf(fp_cpp, ", \"%s\"", _pipeline->_stages.name(s));
 593 
 594   fprintf(fp_cpp, "\n  };\n\n");
 595   fprintf(fp_cpp, "  return (s <= %d ? _stage_names[s] : \"???\");\n",
 596     _pipeline->_stagecnt);
 597   fprintf(fp_cpp, "}\n");
 598   fprintf(fp_cpp, "#endif\n\n");
 599 
 600   fprintf(fp_cpp, "uint Pipeline::functional_unit_latency(uint start, const Pipeline *pred) const {\n");
 601   fprintf(fp_cpp, "  // See if the functional units overlap\n");
 602 #if 0
 603   fprintf(fp_cpp, "\n#ifndef PRODUCT\n");
 604   fprintf(fp_cpp, "  if (TraceOptoOutput) {\n");
 605   fprintf(fp_cpp, "    tty->print(\"#   functional_unit_latency: start == %%d, this->exclusively == 0x%%03x, pred->exclusively == 0x%%03x\\n\", start, resourcesUsedExclusively(), pred->resourcesUsedExclusively());\n");
 606   fprintf(fp_cpp, "  }\n");
 607   fprintf(fp_cpp, "#endif\n\n");
 608 #endif
 609   fprintf(fp_cpp, "  uint mask = resourcesUsedExclusively() & pred->resourcesUsedExclusively();\n");
 610   fprintf(fp_cpp, "  if (mask == 0)\n    return (start);\n\n");
 611 #if 0
 612   fprintf(fp_cpp, "\n#ifndef PRODUCT\n");
 613   fprintf(fp_cpp, "  if (TraceOptoOutput) {\n");
 614   fprintf(fp_cpp, "    tty->print(\"#   functional_unit_latency: mask == 0x%%x\\n\", mask);\n");
 615   fprintf(fp_cpp, "  }\n");
 616   fprintf(fp_cpp, "#endif\n\n");
 617 #endif
 618   fprintf(fp_cpp, "  for (uint i = 0; i < pred->resourceUseCount(); i++) {\n");
 619   fprintf(fp_cpp, "    const Pipeline_Use_Element *predUse = pred->resourceUseElement(i);\n");
 620   fprintf(fp_cpp, "    if (predUse->multiple())\n");
 621   fprintf(fp_cpp, "      continue;\n\n");
 622   fprintf(fp_cpp, "    for (uint j = 0; j < resourceUseCount(); j++) {\n");
 623   fprintf(fp_cpp, "      const Pipeline_Use_Element *currUse = resourceUseElement(j);\n");
 624   fprintf(fp_cpp, "      if (currUse->multiple())\n");
 625   fprintf(fp_cpp, "        continue;\n\n");
 626   fprintf(fp_cpp, "      if (predUse->used() & currUse->used()) {\n");
 627   fprintf(fp_cpp, "        Pipeline_Use_Cycle_Mask x = predUse->mask();\n");
 628   fprintf(fp_cpp, "        Pipeline_Use_Cycle_Mask y = currUse->mask();\n\n");
 629   fprintf(fp_cpp, "        for ( y <<= start; x.overlaps(y); start++ )\n");
 630   fprintf(fp_cpp, "          y <<= 1;\n");
 631   fprintf(fp_cpp, "      }\n");
 632   fprintf(fp_cpp, "    }\n");
 633   fprintf(fp_cpp, "  }\n\n");
 634   fprintf(fp_cpp, "  // There is the potential for overlap\n");
 635   fprintf(fp_cpp, "  return (start);\n");
 636   fprintf(fp_cpp, "}\n\n");
 637   fprintf(fp_cpp, "// The following two routines assume that the root Pipeline_Use entity\n");
 638   fprintf(fp_cpp, "// consists of exactly 1 element for each functional unit\n");
 639   fprintf(fp_cpp, "// start is relative to the current cycle; used for latency-based info\n");
 640   fprintf(fp_cpp, "uint Pipeline_Use::full_latency(uint delay, const Pipeline_Use &pred) const {\n");
 641   fprintf(fp_cpp, "  for (uint i = 0; i < pred._count; i++) {\n");
 642   fprintf(fp_cpp, "    const Pipeline_Use_Element *predUse = pred.element(i);\n");
 643   fprintf(fp_cpp, "    if (predUse->_multiple) {\n");
 644   fprintf(fp_cpp, "      uint min_delay = %d;\n",
 645     _pipeline->_maxcycleused+1);
 646   fprintf(fp_cpp, "      // Multiple possible functional units, choose first unused one\n");
 647   fprintf(fp_cpp, "      for (uint j = predUse->_lb; j <= predUse->_ub; j++) {\n");
 648   fprintf(fp_cpp, "        const Pipeline_Use_Element *currUse = element(j);\n");
 649   fprintf(fp_cpp, "        uint curr_delay = delay;\n");
 650   fprintf(fp_cpp, "        if (predUse->_used & currUse->_used) {\n");
 651   fprintf(fp_cpp, "          Pipeline_Use_Cycle_Mask x = predUse->_mask;\n");
 652   fprintf(fp_cpp, "          Pipeline_Use_Cycle_Mask y = currUse->_mask;\n\n");
 653   fprintf(fp_cpp, "          for ( y <<= curr_delay; x.overlaps(y); curr_delay++ )\n");
 654   fprintf(fp_cpp, "            y <<= 1;\n");
 655   fprintf(fp_cpp, "        }\n");
 656   fprintf(fp_cpp, "        if (min_delay > curr_delay)\n          min_delay = curr_delay;\n");
 657   fprintf(fp_cpp, "      }\n");
 658   fprintf(fp_cpp, "      if (delay < min_delay)\n      delay = min_delay;\n");
 659   fprintf(fp_cpp, "    }\n");
 660   fprintf(fp_cpp, "    else {\n");
 661   fprintf(fp_cpp, "      for (uint j = predUse->_lb; j <= predUse->_ub; j++) {\n");
 662   fprintf(fp_cpp, "        const Pipeline_Use_Element *currUse = element(j);\n");
 663   fprintf(fp_cpp, "        if (predUse->_used & currUse->_used) {\n");
 664   fprintf(fp_cpp, "          Pipeline_Use_Cycle_Mask x = predUse->_mask;\n");
 665   fprintf(fp_cpp, "          Pipeline_Use_Cycle_Mask y = currUse->_mask;\n\n");
 666   fprintf(fp_cpp, "          for ( y <<= delay; x.overlaps(y); delay++ )\n");
 667   fprintf(fp_cpp, "            y <<= 1;\n");
 668   fprintf(fp_cpp, "        }\n");
 669   fprintf(fp_cpp, "      }\n");
 670   fprintf(fp_cpp, "    }\n");
 671   fprintf(fp_cpp, "  }\n\n");
 672   fprintf(fp_cpp, "  return (delay);\n");
 673   fprintf(fp_cpp, "}\n\n");
 674   fprintf(fp_cpp, "void Pipeline_Use::add_usage(const Pipeline_Use &pred) {\n");
 675   fprintf(fp_cpp, "  for (uint i = 0; i < pred._count; i++) {\n");
 676   fprintf(fp_cpp, "    const Pipeline_Use_Element *predUse = pred.element(i);\n");
 677   fprintf(fp_cpp, "    if (predUse->_multiple) {\n");
 678   fprintf(fp_cpp, "      // Multiple possible functional units, choose first unused one\n");
 679   fprintf(fp_cpp, "      for (uint j = predUse->_lb; j <= predUse->_ub; j++) {\n");
 680   fprintf(fp_cpp, "        Pipeline_Use_Element *currUse = element(j);\n");
 681   fprintf(fp_cpp, "        if ( !predUse->_mask.overlaps(currUse->_mask) ) {\n");
 682   fprintf(fp_cpp, "          currUse->_used |= (1 << j);\n");
 683   fprintf(fp_cpp, "          _resources_used |= (1 << j);\n");
 684   fprintf(fp_cpp, "          currUse->_mask.Or(predUse->_mask);\n");
 685   fprintf(fp_cpp, "          break;\n");
 686   fprintf(fp_cpp, "        }\n");
 687   fprintf(fp_cpp, "      }\n");
 688   fprintf(fp_cpp, "    }\n");
 689   fprintf(fp_cpp, "    else {\n");
 690   fprintf(fp_cpp, "      for (uint j = predUse->_lb; j <= predUse->_ub; j++) {\n");
 691   fprintf(fp_cpp, "        Pipeline_Use_Element *currUse = element(j);\n");
 692   fprintf(fp_cpp, "        currUse->_used |= (1 << j);\n");
 693   fprintf(fp_cpp, "        _resources_used |= (1 << j);\n");
 694   fprintf(fp_cpp, "        currUse->_mask.Or(predUse->_mask);\n");
 695   fprintf(fp_cpp, "      }\n");
 696   fprintf(fp_cpp, "    }\n");
 697   fprintf(fp_cpp, "  }\n");
 698   fprintf(fp_cpp, "}\n\n");
 699 
 700   fprintf(fp_cpp, "uint Pipeline::operand_latency(uint opnd, const Pipeline *pred) const {\n");
 701   fprintf(fp_cpp, "  int const default_latency = 1;\n");
 702   fprintf(fp_cpp, "\n");
 703 #if 0
 704   fprintf(fp_cpp, "#ifndef PRODUCT\n");
 705   fprintf(fp_cpp, "  if (TraceOptoOutput) {\n");
 706   fprintf(fp_cpp, "    tty->print(\"#   operand_latency(%%d), _read_stage_count = %%d\\n\", opnd, _read_stage_count);\n");
 707   fprintf(fp_cpp, "  }\n");
 708   fprintf(fp_cpp, "#endif\n\n");
 709 #endif
 710   fprintf(fp_cpp, "  assert(this, \"NULL pipeline info\");\n");
 711   fprintf(fp_cpp, "  assert(pred, \"NULL predecessor pipline info\");\n\n");
 712   fprintf(fp_cpp, "  if (pred->hasFixedLatency())\n    return (pred->fixedLatency());\n\n");
 713   fprintf(fp_cpp, "  // If this is not an operand, then assume a dependence with 0 latency\n");
 714   fprintf(fp_cpp, "  if (opnd > _read_stage_count)\n    return (0);\n\n");
 715   fprintf(fp_cpp, "  uint writeStage = pred->_write_stage;\n");
 716   fprintf(fp_cpp, "  uint readStage  = _read_stages[opnd-1];\n");
 717 #if 0
 718   fprintf(fp_cpp, "\n#ifndef PRODUCT\n");
 719   fprintf(fp_cpp, "  if (TraceOptoOutput) {\n");
 720   fprintf(fp_cpp, "    tty->print(\"#   operand_latency: writeStage=%%s readStage=%%s, opnd=%%d\\n\", stageName(writeStage), stageName(readStage), opnd);\n");
 721   fprintf(fp_cpp, "  }\n");
 722   fprintf(fp_cpp, "#endif\n\n");
 723 #endif
 724   fprintf(fp_cpp, "\n");
 725   fprintf(fp_cpp, "  if (writeStage == stage_undefined || readStage == stage_undefined)\n");
 726   fprintf(fp_cpp, "    return (default_latency);\n");
 727   fprintf(fp_cpp, "\n");
 728   fprintf(fp_cpp, "  int delta = writeStage - readStage;\n");
 729   fprintf(fp_cpp, "  if (delta < 0) delta = 0;\n\n");
 730 #if 0
 731   fprintf(fp_cpp, "\n#ifndef PRODUCT\n");
 732   fprintf(fp_cpp, "  if (TraceOptoOutput) {\n");
 733   fprintf(fp_cpp, "    tty->print(\"# operand_latency: delta=%%d\\n\", delta);\n");
 734   fprintf(fp_cpp, "  }\n");
 735   fprintf(fp_cpp, "#endif\n\n");
 736 #endif
 737   fprintf(fp_cpp, "  return (delta);\n");
 738   fprintf(fp_cpp, "}\n\n");
 739 
 740   if (!_pipeline)
 741     /* Do Nothing */;
 742 
 743   else if (_pipeline->_maxcycleused <=
 744 #ifdef SPARC
 745     64
 746 #else
 747     32
 748 #endif
 749       ) {
 750     fprintf(fp_cpp, "Pipeline_Use_Cycle_Mask operator&(const Pipeline_Use_Cycle_Mask &in1, const Pipeline_Use_Cycle_Mask &in2) {\n");
 751     fprintf(fp_cpp, "  return Pipeline_Use_Cycle_Mask(in1._mask & in2._mask);\n");
 752     fprintf(fp_cpp, "}\n\n");
 753     fprintf(fp_cpp, "Pipeline_Use_Cycle_Mask operator|(const Pipeline_Use_Cycle_Mask &in1, const Pipeline_Use_Cycle_Mask &in2) {\n");
 754     fprintf(fp_cpp, "  return Pipeline_Use_Cycle_Mask(in1._mask | in2._mask);\n");
 755     fprintf(fp_cpp, "}\n\n");
 756   }
 757   else {
 758     uint l;
 759     uint masklen = (_pipeline->_maxcycleused + 31) >> 5;
 760     fprintf(fp_cpp, "Pipeline_Use_Cycle_Mask operator&(const Pipeline_Use_Cycle_Mask &in1, const Pipeline_Use_Cycle_Mask &in2) {\n");
 761     fprintf(fp_cpp, "  return Pipeline_Use_Cycle_Mask(");
 762     for (l = 1; l <= masklen; l++)
 763       fprintf(fp_cpp, "in1._mask%d & in2._mask%d%s\n", l, l, l < masklen ? ", " : "");
 764     fprintf(fp_cpp, ");\n");
 765     fprintf(fp_cpp, "}\n\n");
 766     fprintf(fp_cpp, "Pipeline_Use_Cycle_Mask operator|(const Pipeline_Use_Cycle_Mask &in1, const Pipeline_Use_Cycle_Mask &in2) {\n");
 767     fprintf(fp_cpp, "  return Pipeline_Use_Cycle_Mask(");
 768     for (l = 1; l <= masklen; l++)
 769       fprintf(fp_cpp, "in1._mask%d | in2._mask%d%s", l, l, l < masklen ? ", " : "");
 770     fprintf(fp_cpp, ");\n");
 771     fprintf(fp_cpp, "}\n\n");
 772     fprintf(fp_cpp, "void Pipeline_Use_Cycle_Mask::Or(const Pipeline_Use_Cycle_Mask &in2) {\n ");
 773     for (l = 1; l <= masklen; l++)
 774       fprintf(fp_cpp, " _mask%d |= in2._mask%d;", l, l);
 775     fprintf(fp_cpp, "\n}\n\n");
 776   }
 777 
 778   /* Get the length of all the resource names */
 779   for (_pipeline->_reslist.reset(), resourcenamelen = 0;
 780        (resourcename = _pipeline->_reslist.iter()) != NULL;
 781        resourcenamelen += (int)strlen(resourcename));
 782 
 783   // Create the pipeline class description
 784 
 785   fprintf(fp_cpp, "static const Pipeline pipeline_class_Zero_Instructions(0, 0, true, 0, 0, false, false, false, false, NULL, NULL, NULL, Pipeline_Use(0, 0, 0, NULL));\n\n");
 786   fprintf(fp_cpp, "static const Pipeline pipeline_class_Unknown_Instructions(0, 0, true, 0, 0, false, true, true, false, NULL, NULL, NULL, Pipeline_Use(0, 0, 0, NULL));\n\n");
 787 
 788   fprintf(fp_cpp, "const Pipeline_Use_Element Pipeline_Use::elaborated_elements[%d] = {\n", _pipeline->_rescount);
 789   for (int i1 = 0; i1 < _pipeline->_rescount; i1++) {
 790     fprintf(fp_cpp, "  Pipeline_Use_Element(0, %d, %d, false, Pipeline_Use_Cycle_Mask(", i1, i1);
 791     uint masklen = (_pipeline->_maxcycleused + 31) >> 5;
 792     for (int i2 = masklen-1; i2 >= 0; i2--)
 793       fprintf(fp_cpp, "0%s", i2 > 0 ? ", " : "");
 794     fprintf(fp_cpp, "))%s\n", i1 < (_pipeline->_rescount-1) ? "," : "");
 795   }
 796   fprintf(fp_cpp, "};\n\n");
 797 
 798   fprintf(fp_cpp, "const Pipeline_Use Pipeline_Use::elaborated_use(0, 0, %d, (Pipeline_Use_Element *)&elaborated_elements[0]);\n\n",
 799     _pipeline->_rescount);
 800 
 801   for (_pipeline->_classlist.reset(); (classname = _pipeline->_classlist.iter()) != NULL; ) {
 802     fprintf(fp_cpp, "\n");
 803     fprintf(fp_cpp, "// Pipeline Class \"%s\"\n", classname);
 804     PipeClassForm *pipeclass = _pipeline->_classdict[classname]->is_pipeclass();
 805     int maxWriteStage = -1;
 806     int maxMoreInstrs = 0;
 807     int paramcount = 0;
 808     int i = 0;
 809     const char *paramname;
 810     int resource_count = (_pipeline->_rescount + 3) >> 2;
 811 
 812     // Scan the operands, looking for last output stage and number of inputs
 813     for (pipeclass->_parameters.reset(); (paramname = pipeclass->_parameters.iter()) != NULL; ) {
 814       const PipeClassOperandForm *pipeopnd =
 815           (const PipeClassOperandForm *)pipeclass->_localUsage[paramname];
 816       if (pipeopnd) {
 817         if (pipeopnd->_iswrite) {
 818            int stagenum  = _pipeline->_stages.index(pipeopnd->_stage);
 819            int moreinsts = pipeopnd->_more_instrs;
 820           if ((maxWriteStage+maxMoreInstrs) < (stagenum+moreinsts)) {
 821             maxWriteStage = stagenum;
 822             maxMoreInstrs = moreinsts;
 823           }
 824         }
 825       }
 826 
 827       if (i++ > 0 || (pipeopnd && !pipeopnd->isWrite()))
 828         paramcount++;
 829     }
 830 
 831     // Create the list of stages for the operands that are read
 832     // Note that we will build a NameList to reduce the number of copies
 833 
 834     int pipeline_reads_index = pipeline_reads_initializer(fp_cpp, pipeline_reads, pipeclass);
 835 
 836     int pipeline_res_stages_index = pipeline_res_stages_initializer(
 837       fp_cpp, _pipeline, pipeline_res_stages, pipeclass);
 838 
 839     int pipeline_res_cycles_index = pipeline_res_cycles_initializer(
 840       fp_cpp, _pipeline, pipeline_res_cycles, pipeclass);
 841 
 842     int pipeline_res_mask_index = pipeline_res_mask_initializer(
 843       fp_cpp, _pipeline, pipeline_res_masks, pipeline_res_args, pipeclass);
 844 
 845 #if 0
 846     // Process the Resources
 847     const PipeClassResourceForm *piperesource;
 848 
 849     unsigned resources_used = 0;
 850     unsigned exclusive_resources_used = 0;
 851     unsigned resource_groups = 0;
 852     for (pipeclass->_resUsage.reset();
 853          (piperesource = (const PipeClassResourceForm *)pipeclass->_resUsage.iter()) != NULL; ) {
 854       int used_mask = _pipeline->_resdict[piperesource->_resource]->is_resource()->mask();
 855       if (used_mask)
 856         resource_groups++;
 857       resources_used |= used_mask;
 858       if ((used_mask & (used_mask-1)) == 0)
 859         exclusive_resources_used |= used_mask;
 860     }
 861 
 862     if (resource_groups > 0) {
 863       fprintf(fp_cpp, "static const uint pipeline_res_or_masks_%03d[%d] = {",
 864         pipeclass->_num, resource_groups);
 865       for (pipeclass->_resUsage.reset(), i = 1;
 866            (piperesource = (const PipeClassResourceForm *)pipeclass->_resUsage.iter()) != NULL;
 867            i++ ) {
 868         int used_mask = _pipeline->_resdict[piperesource->_resource]->is_resource()->mask();
 869         if (used_mask) {
 870           fprintf(fp_cpp, " 0x%0*x%c", resource_count, used_mask, i < (int)resource_groups ? ',' : ' ');
 871         }
 872       }
 873       fprintf(fp_cpp, "};\n\n");
 874     }
 875 #endif
 876 
 877     // Create the pipeline class description
 878     fprintf(fp_cpp, "static const Pipeline pipeline_class_%03d(",
 879       pipeclass->_num);
 880     if (maxWriteStage < 0)
 881       fprintf(fp_cpp, "(uint)stage_undefined");
 882     else if (maxMoreInstrs == 0)
 883       fprintf(fp_cpp, "(uint)stage_%s", _pipeline->_stages.name(maxWriteStage));
 884     else
 885       fprintf(fp_cpp, "((uint)stage_%s)+%d", _pipeline->_stages.name(maxWriteStage), maxMoreInstrs);
 886     fprintf(fp_cpp, ", %d, %s, %d, %d, %s, %s, %s, %s,\n",
 887       paramcount,
 888       pipeclass->hasFixedLatency() ? "true" : "false",
 889       pipeclass->fixedLatency(),
 890       pipeclass->InstructionCount(),
 891       pipeclass->hasBranchDelay() ? "true" : "false",
 892       pipeclass->hasMultipleBundles() ? "true" : "false",
 893       pipeclass->forceSerialization() ? "true" : "false",
 894       pipeclass->mayHaveNoCode() ? "true" : "false" );
 895     if (paramcount > 0) {
 896       fprintf(fp_cpp, "\n  (enum machPipelineStages * const) pipeline_reads_%03d,\n ",
 897         pipeline_reads_index+1);
 898     }
 899     else
 900       fprintf(fp_cpp, " NULL,");
 901     fprintf(fp_cpp, "  (enum machPipelineStages * const) pipeline_res_stages_%03d,\n",
 902       pipeline_res_stages_index+1);
 903     fprintf(fp_cpp, "  (uint * const) pipeline_res_cycles_%03d,\n",
 904       pipeline_res_cycles_index+1);
 905     fprintf(fp_cpp, "  Pipeline_Use(%s, (Pipeline_Use_Element *)",
 906       pipeline_res_args.name(pipeline_res_mask_index));
 907     if (strlen(pipeline_res_masks.name(pipeline_res_mask_index)) > 0)
 908       fprintf(fp_cpp, "&pipeline_res_mask_%03d[0]",
 909         pipeline_res_mask_index+1);
 910     else
 911       fprintf(fp_cpp, "NULL");
 912     fprintf(fp_cpp, "));\n");
 913   }
 914 
 915   // Generate the Node::latency method if _pipeline defined
 916   fprintf(fp_cpp, "\n");
 917   fprintf(fp_cpp, "//------------------Inter-Instruction Latency--------------------------------\n");
 918   fprintf(fp_cpp, "uint Node::latency(uint i) {\n");
 919   if (_pipeline) {
 920 #if 0
 921     fprintf(fp_cpp, "#ifndef PRODUCT\n");
 922     fprintf(fp_cpp, " if (TraceOptoOutput) {\n");
 923     fprintf(fp_cpp, "    tty->print(\"# %%4d->latency(%%d)\\n\", _idx, i);\n");
 924     fprintf(fp_cpp, " }\n");
 925     fprintf(fp_cpp, "#endif\n");
 926 #endif
 927     fprintf(fp_cpp, "  uint j;\n");
 928     fprintf(fp_cpp, "  // verify in legal range for inputs\n");
 929     fprintf(fp_cpp, "  assert(i < len(), \"index not in range\");\n\n");
 930     fprintf(fp_cpp, "  // verify input is not null\n");
 931     fprintf(fp_cpp, "  Node *pred = in(i);\n");
 932     fprintf(fp_cpp, "  if (!pred)\n    return %d;\n\n",
 933       non_operand_latency);
 934     fprintf(fp_cpp, "  if (pred->is_Proj())\n    pred = pred->in(0);\n\n");
 935     fprintf(fp_cpp, "  // if either node does not have pipeline info, use default\n");
 936     fprintf(fp_cpp, "  const Pipeline *predpipe = pred->pipeline();\n");
 937     fprintf(fp_cpp, "  assert(predpipe, \"no predecessor pipeline info\");\n\n");
 938     fprintf(fp_cpp, "  if (predpipe->hasFixedLatency())\n    return predpipe->fixedLatency();\n\n");
 939     fprintf(fp_cpp, "  const Pipeline *currpipe = pipeline();\n");
 940     fprintf(fp_cpp, "  assert(currpipe, \"no pipeline info\");\n\n");
 941     fprintf(fp_cpp, "  if (!is_Mach())\n    return %d;\n\n",
 942       node_latency);
 943     fprintf(fp_cpp, "  const MachNode *m = as_Mach();\n");
 944     fprintf(fp_cpp, "  j = m->oper_input_base();\n");
 945     fprintf(fp_cpp, "  if (i < j)\n    return currpipe->functional_unit_latency(%d, predpipe);\n\n",
 946       non_operand_latency);
 947     fprintf(fp_cpp, "  // determine which operand this is in\n");
 948     fprintf(fp_cpp, "  uint n = m->num_opnds();\n");
 949     fprintf(fp_cpp, "  int delta = %d;\n\n",
 950       non_operand_latency);
 951     fprintf(fp_cpp, "  uint k;\n");
 952     fprintf(fp_cpp, "  for (k = 1; k < n; k++) {\n");
 953     fprintf(fp_cpp, "    j += m->_opnds[k]->num_edges();\n");
 954     fprintf(fp_cpp, "    if (i < j)\n");
 955     fprintf(fp_cpp, "      break;\n");
 956     fprintf(fp_cpp, "  }\n");
 957     fprintf(fp_cpp, "  if (k < n)\n");
 958     fprintf(fp_cpp, "    delta = currpipe->operand_latency(k,predpipe);\n\n");
 959     fprintf(fp_cpp, "  return currpipe->functional_unit_latency(delta, predpipe);\n");
 960   }
 961   else {
 962     fprintf(fp_cpp, "  // assert(false, \"pipeline functionality is not defined\");\n");
 963     fprintf(fp_cpp, "  return %d;\n",
 964       non_operand_latency);
 965   }
 966   fprintf(fp_cpp, "}\n\n");
 967 
 968   // Output the list of nop nodes
 969   fprintf(fp_cpp, "// Descriptions for emitting different functional unit nops\n");
 970   const char *nop;
 971   int nopcnt = 0;
 972   for ( _pipeline->_noplist.reset(); (nop = _pipeline->_noplist.iter()) != NULL; nopcnt++ );
 973 
 974   fprintf(fp_cpp, "void Bundle::initialize_nops(MachNode * nop_list[%d], Compile *C) {\n", nopcnt);
 975   int i = 0;
 976   for ( _pipeline->_noplist.reset(); (nop = _pipeline->_noplist.iter()) != NULL; i++ ) {
 977     fprintf(fp_cpp, "  nop_list[%d] = (MachNode *) new (C) %sNode();\n", i, nop);
 978   }
 979   fprintf(fp_cpp, "};\n\n");
 980   fprintf(fp_cpp, "#ifndef PRODUCT\n");
 981   fprintf(fp_cpp, "void Bundle::dump(outputStream *st) const {\n");
 982   fprintf(fp_cpp, "  static const char * bundle_flags[] = {\n");
 983   fprintf(fp_cpp, "    \"\",\n");
 984   fprintf(fp_cpp, "    \"use nop delay\",\n");
 985   fprintf(fp_cpp, "    \"use unconditional delay\",\n");
 986   fprintf(fp_cpp, "    \"use conditional delay\",\n");
 987   fprintf(fp_cpp, "    \"used in conditional delay\",\n");
 988   fprintf(fp_cpp, "    \"used in unconditional delay\",\n");
 989   fprintf(fp_cpp, "    \"used in all conditional delays\",\n");
 990   fprintf(fp_cpp, "  };\n\n");
 991 
 992   fprintf(fp_cpp, "  static const char *resource_names[%d] = {", _pipeline->_rescount);
 993   for (i = 0; i < _pipeline->_rescount; i++)
 994     fprintf(fp_cpp, " \"%s\"%c", _pipeline->_reslist.name(i), i < _pipeline->_rescount-1 ? ',' : ' ');
 995   fprintf(fp_cpp, "};\n\n");
 996 
 997   // See if the same string is in the table
 998   fprintf(fp_cpp, "  bool needs_comma = false;\n\n");
 999   fprintf(fp_cpp, "  if (_flags) {\n");
1000   fprintf(fp_cpp, "    st->print(\"%%s\", bundle_flags[_flags]);\n");
1001   fprintf(fp_cpp, "    needs_comma = true;\n");
1002   fprintf(fp_cpp, "  };\n");
1003   fprintf(fp_cpp, "  if (instr_count()) {\n");
1004   fprintf(fp_cpp, "    st->print(\"%%s%%d instr%%s\", needs_comma ? \", \" : \"\", instr_count(), instr_count() != 1 ? \"s\" : \"\");\n");
1005   fprintf(fp_cpp, "    needs_comma = true;\n");
1006   fprintf(fp_cpp, "  };\n");
1007   fprintf(fp_cpp, "  uint r = resources_used();\n");
1008   fprintf(fp_cpp, "  if (r) {\n");
1009   fprintf(fp_cpp, "    st->print(\"%%sresource%%s:\", needs_comma ? \", \" : \"\", (r & (r-1)) != 0 ? \"s\" : \"\");\n");
1010   fprintf(fp_cpp, "    for (uint i = 0; i < %d; i++)\n", _pipeline->_rescount);
1011   fprintf(fp_cpp, "      if ((r & (1 << i)) != 0)\n");
1012   fprintf(fp_cpp, "        st->print(\" %%s\", resource_names[i]);\n");
1013   fprintf(fp_cpp, "    needs_comma = true;\n");
1014   fprintf(fp_cpp, "  };\n");
1015   fprintf(fp_cpp, "  st->print(\"\\n\");\n");
1016   fprintf(fp_cpp, "}\n");
1017   fprintf(fp_cpp, "#endif\n");
1018 }
1019 
1020 // ---------------------------------------------------------------------------
1021 //------------------------------Utilities to build Instruction Classes--------
1022 // ---------------------------------------------------------------------------
1023 
1024 static void defineOut_RegMask(FILE *fp, const char *node, const char *regMask) {
1025   fprintf(fp,"const RegMask &%sNode::out_RegMask() const { return (%s); }\n",
1026           node, regMask);
1027 }
1028 
1029 static void print_block_index(FILE *fp, int inst_position) {
1030   assert( inst_position >= 0, "Instruction number less than zero");
1031   fprintf(fp, "block_index");
1032   if( inst_position != 0 ) {
1033     fprintf(fp, " - %d", inst_position);
1034   }
1035 }
1036 
1037 // Scan the peepmatch and output a test for each instruction
1038 static void check_peepmatch_instruction_sequence(FILE *fp, PeepMatch *pmatch, PeepConstraint *pconstraint) {
1039   int         parent        = -1;
1040   int         inst_position = 0;
1041   const char* inst_name     = NULL;
1042   int         input         = 0;
1043   fprintf(fp, "  // Check instruction sub-tree\n");
1044   pmatch->reset();
1045   for( pmatch->next_instruction( parent, inst_position, inst_name, input );
1046        inst_name != NULL;
1047        pmatch->next_instruction( parent, inst_position, inst_name, input ) ) {
1048     // If this is not a placeholder
1049     if( ! pmatch->is_placeholder() ) {
1050       // Define temporaries 'inst#', based on parent and parent's input index
1051       if( parent != -1 ) {                // root was initialized
1052         fprintf(fp, "  // Identify previous instruction if inside this block\n");
1053         fprintf(fp, "  if( ");
1054         print_block_index(fp, inst_position);
1055         fprintf(fp, " > 0 ) {\n    Node *n = block->get_node(");
1056         print_block_index(fp, inst_position);
1057         fprintf(fp, ");\n    inst%d = (n->is_Mach()) ? ", inst_position);
1058         fprintf(fp, "n->as_Mach() : NULL;\n  }\n");
1059       }
1060 
1061       // When not the root
1062       // Test we have the correct instruction by comparing the rule.
1063       if( parent != -1 ) {
1064         fprintf(fp, "  matches = matches && (inst%d != NULL) && (inst%d->rule() == %s_rule);\n",
1065                 inst_position, inst_position, inst_name);
1066       }
1067     } else {
1068       // Check that user did not try to constrain a placeholder
1069       assert( ! pconstraint->constrains_instruction(inst_position),
1070               "fatal(): Can not constrain a placeholder instruction");
1071     }
1072   }
1073 }
1074 
1075 // Build mapping for register indices, num_edges to input
1076 static void build_instruction_index_mapping( FILE *fp, FormDict &globals, PeepMatch *pmatch ) {
1077   int         parent        = -1;
1078   int         inst_position = 0;
1079   const char* inst_name     = NULL;
1080   int         input         = 0;
1081   fprintf(fp, "      // Build map to register info\n");
1082   pmatch->reset();
1083   for( pmatch->next_instruction( parent, inst_position, inst_name, input );
1084        inst_name != NULL;
1085        pmatch->next_instruction( parent, inst_position, inst_name, input ) ) {
1086     // If this is not a placeholder
1087     if( ! pmatch->is_placeholder() ) {
1088       // Define temporaries 'inst#', based on self's inst_position
1089       InstructForm *inst = globals[inst_name]->is_instruction();
1090       if( inst != NULL ) {
1091         char inst_prefix[]  = "instXXXX_";
1092         sprintf(inst_prefix, "inst%d_",   inst_position);
1093         char receiver[]     = "instXXXX->";
1094         sprintf(receiver,    "inst%d->", inst_position);
1095         inst->index_temps( fp, globals, inst_prefix, receiver );
1096       }
1097     }
1098   }
1099 }
1100 
1101 // Generate tests for the constraints
1102 static void check_peepconstraints(FILE *fp, FormDict &globals, PeepMatch *pmatch, PeepConstraint *pconstraint) {
1103   fprintf(fp, "\n");
1104   fprintf(fp, "      // Check constraints on sub-tree-leaves\n");
1105 
1106   // Build mapping from num_edges to local variables
1107   build_instruction_index_mapping( fp, globals, pmatch );
1108 
1109   // Build constraint tests
1110   if( pconstraint != NULL ) {
1111     fprintf(fp, "      matches = matches &&");
1112     bool   first_constraint = true;
1113     while( pconstraint != NULL ) {
1114       // indentation and connecting '&&'
1115       const char *indentation = "      ";
1116       fprintf(fp, "\n%s%s", indentation, (!first_constraint ? "&& " : "  "));
1117 
1118       // Only have '==' relation implemented
1119       if( strcmp(pconstraint->_relation,"==") != 0 ) {
1120         assert( false, "Unimplemented()" );
1121       }
1122 
1123       // LEFT
1124       int left_index       = pconstraint->_left_inst;
1125       const char *left_op  = pconstraint->_left_op;
1126       // Access info on the instructions whose operands are compared
1127       InstructForm *inst_left = globals[pmatch->instruction_name(left_index)]->is_instruction();
1128       assert( inst_left, "Parser should guaranty this is an instruction");
1129       int left_op_base  = inst_left->oper_input_base(globals);
1130       // Access info on the operands being compared
1131       int left_op_index  = inst_left->operand_position(left_op, Component::USE);
1132       if( left_op_index == -1 ) {
1133         left_op_index = inst_left->operand_position(left_op, Component::DEF);
1134         if( left_op_index == -1 ) {
1135           left_op_index = inst_left->operand_position(left_op, Component::USE_DEF);
1136         }
1137       }
1138       assert( left_op_index  != NameList::Not_in_list, "Did not find operand in instruction");
1139       ComponentList components_left = inst_left->_components;
1140       const char *left_comp_type = components_left.at(left_op_index)->_type;
1141       OpClassForm *left_opclass = globals[left_comp_type]->is_opclass();
1142       Form::InterfaceType left_interface_type = left_opclass->interface_type(globals);
1143 
1144 
1145       // RIGHT
1146       int right_op_index = -1;
1147       int right_index      = pconstraint->_right_inst;
1148       const char *right_op = pconstraint->_right_op;
1149       if( right_index != -1 ) { // Match operand
1150         // Access info on the instructions whose operands are compared
1151         InstructForm *inst_right = globals[pmatch->instruction_name(right_index)]->is_instruction();
1152         assert( inst_right, "Parser should guaranty this is an instruction");
1153         int right_op_base = inst_right->oper_input_base(globals);
1154         // Access info on the operands being compared
1155         right_op_index = inst_right->operand_position(right_op, Component::USE);
1156         if( right_op_index == -1 ) {
1157           right_op_index = inst_right->operand_position(right_op, Component::DEF);
1158           if( right_op_index == -1 ) {
1159             right_op_index = inst_right->operand_position(right_op, Component::USE_DEF);
1160           }
1161         }
1162         assert( right_op_index != NameList::Not_in_list, "Did not find operand in instruction");
1163         ComponentList components_right = inst_right->_components;
1164         const char *right_comp_type = components_right.at(right_op_index)->_type;
1165         OpClassForm *right_opclass = globals[right_comp_type]->is_opclass();
1166         Form::InterfaceType right_interface_type = right_opclass->interface_type(globals);
1167         assert( right_interface_type == left_interface_type, "Both must be same interface");
1168 
1169       } else {                  // Else match register
1170         // assert( false, "should be a register" );
1171       }
1172 
1173       //
1174       // Check for equivalence
1175       //
1176       // fprintf(fp, "phase->eqv( ");
1177       // fprintf(fp, "inst%d->in(%d+%d) /* %s */, inst%d->in(%d+%d) /* %s */",
1178       //         left_index,  left_op_base,  left_op_index,  left_op,
1179       //         right_index, right_op_base, right_op_index, right_op );
1180       // fprintf(fp, ")");
1181       //
1182       switch( left_interface_type ) {
1183       case Form::register_interface: {
1184         // Check that they are allocated to the same register
1185         // Need parameter for index position if not result operand
1186         char left_reg_index[] = ",instXXXX_idxXXXX";
1187         if( left_op_index != 0 ) {
1188           assert( (left_index <= 9999) && (left_op_index <= 9999), "exceed string size");
1189           // Must have index into operands
1190           sprintf(left_reg_index,",inst%d_idx%d", (int)left_index, left_op_index);
1191         } else {
1192           strcpy(left_reg_index, "");
1193         }
1194         fprintf(fp, "(inst%d->_opnds[%d]->reg(ra_,inst%d%s)  /* %d.%s */",
1195                 left_index,  left_op_index, left_index, left_reg_index, left_index, left_op );
1196         fprintf(fp, " == ");
1197 
1198         if( right_index != -1 ) {
1199           char right_reg_index[18] = ",instXXXX_idxXXXX";
1200           if( right_op_index != 0 ) {
1201             assert( (right_index <= 9999) && (right_op_index <= 9999), "exceed string size");
1202             // Must have index into operands
1203             sprintf(right_reg_index,",inst%d_idx%d", (int)right_index, right_op_index);
1204           } else {
1205             strcpy(right_reg_index, "");
1206           }
1207           fprintf(fp, "/* %d.%s */ inst%d->_opnds[%d]->reg(ra_,inst%d%s)",
1208                   right_index, right_op, right_index, right_op_index, right_index, right_reg_index );
1209         } else {
1210           fprintf(fp, "%s_enc", right_op );
1211         }
1212         fprintf(fp,")");
1213         break;
1214       }
1215       case Form::constant_interface: {
1216         // Compare the '->constant()' values
1217         fprintf(fp, "(inst%d->_opnds[%d]->constant()  /* %d.%s */",
1218                 left_index,  left_op_index,  left_index, left_op );
1219         fprintf(fp, " == ");
1220         fprintf(fp, "/* %d.%s */ inst%d->_opnds[%d]->constant())",
1221                 right_index, right_op, right_index, right_op_index );
1222         break;
1223       }
1224       case Form::memory_interface: {
1225         // Compare 'base', 'index', 'scale', and 'disp'
1226         // base
1227         fprintf(fp, "( \n");
1228         fprintf(fp, "  (inst%d->_opnds[%d]->base(ra_,inst%d,inst%d_idx%d)  /* %d.%s$$base */",
1229           left_index, left_op_index, left_index, left_index, left_op_index, left_index, left_op );
1230         fprintf(fp, " == ");
1231         fprintf(fp, "/* %d.%s$$base */ inst%d->_opnds[%d]->base(ra_,inst%d,inst%d_idx%d)) &&\n",
1232                 right_index, right_op, right_index, right_op_index, right_index, right_index, right_op_index );
1233         // index
1234         fprintf(fp, "  (inst%d->_opnds[%d]->index(ra_,inst%d,inst%d_idx%d)  /* %d.%s$$index */",
1235                 left_index, left_op_index, left_index, left_index, left_op_index, left_index, left_op );
1236         fprintf(fp, " == ");
1237         fprintf(fp, "/* %d.%s$$index */ inst%d->_opnds[%d]->index(ra_,inst%d,inst%d_idx%d)) &&\n",
1238                 right_index, right_op, right_index, right_op_index, right_index, right_index, right_op_index );
1239         // scale
1240         fprintf(fp, "  (inst%d->_opnds[%d]->scale()  /* %d.%s$$scale */",
1241                 left_index,  left_op_index,  left_index, left_op );
1242         fprintf(fp, " == ");
1243         fprintf(fp, "/* %d.%s$$scale */ inst%d->_opnds[%d]->scale()) &&\n",
1244                 right_index, right_op, right_index, right_op_index );
1245         // disp
1246         fprintf(fp, "  (inst%d->_opnds[%d]->disp(ra_,inst%d,inst%d_idx%d)  /* %d.%s$$disp */",
1247                 left_index, left_op_index, left_index, left_index, left_op_index, left_index, left_op );
1248         fprintf(fp, " == ");
1249         fprintf(fp, "/* %d.%s$$disp */ inst%d->_opnds[%d]->disp(ra_,inst%d,inst%d_idx%d))\n",
1250                 right_index, right_op, right_index, right_op_index, right_index, right_index, right_op_index );
1251         fprintf(fp, ") \n");
1252         break;
1253       }
1254       case Form::conditional_interface: {
1255         // Compare the condition code being tested
1256         assert( false, "Unimplemented()" );
1257         break;
1258       }
1259       default: {
1260         assert( false, "ShouldNotReachHere()" );
1261         break;
1262       }
1263       }
1264 
1265       // Advance to next constraint
1266       pconstraint = pconstraint->next();
1267       first_constraint = false;
1268     }
1269 
1270     fprintf(fp, ";\n");
1271   }
1272 }
1273 
1274 // // EXPERIMENTAL -- TEMPORARY code
1275 // static Form::DataType get_operand_type(FormDict &globals, InstructForm *instr, const char *op_name ) {
1276 //   int op_index = instr->operand_position(op_name, Component::USE);
1277 //   if( op_index == -1 ) {
1278 //     op_index = instr->operand_position(op_name, Component::DEF);
1279 //     if( op_index == -1 ) {
1280 //       op_index = instr->operand_position(op_name, Component::USE_DEF);
1281 //     }
1282 //   }
1283 //   assert( op_index != NameList::Not_in_list, "Did not find operand in instruction");
1284 //
1285 //   ComponentList components_right = instr->_components;
1286 //   char *right_comp_type = components_right.at(op_index)->_type;
1287 //   OpClassForm *right_opclass = globals[right_comp_type]->is_opclass();
1288 //   Form::InterfaceType  right_interface_type = right_opclass->interface_type(globals);
1289 //
1290 //   return;
1291 // }
1292 
1293 // Construct the new sub-tree
1294 static void generate_peepreplace( FILE *fp, FormDict &globals, PeepMatch *pmatch, PeepConstraint *pconstraint, PeepReplace *preplace, int max_position ) {
1295   fprintf(fp, "      // IF instructions and constraints matched\n");
1296   fprintf(fp, "      if( matches ) {\n");
1297   fprintf(fp, "        // generate the new sub-tree\n");
1298   fprintf(fp, "        assert( true, \"Debug stopping point\");\n");
1299   if( preplace != NULL ) {
1300     // Get the root of the new sub-tree
1301     const char *root_inst = NULL;
1302     preplace->next_instruction(root_inst);
1303     InstructForm *root_form = globals[root_inst]->is_instruction();
1304     assert( root_form != NULL, "Replacement instruction was not previously defined");
1305     fprintf(fp, "        %sNode *root = new (C) %sNode();\n", root_inst, root_inst);
1306 
1307     int         inst_num;
1308     const char *op_name;
1309     int         opnds_index = 0;            // define result operand
1310     // Then install the use-operands for the new sub-tree
1311     // preplace->reset();             // reset breaks iteration
1312     for( preplace->next_operand( inst_num, op_name );
1313          op_name != NULL;
1314          preplace->next_operand( inst_num, op_name ) ) {
1315       InstructForm *inst_form;
1316       inst_form  = globals[pmatch->instruction_name(inst_num)]->is_instruction();
1317       assert( inst_form, "Parser should guaranty this is an instruction");
1318       int inst_op_num = inst_form->operand_position(op_name, Component::USE);
1319       if( inst_op_num == NameList::Not_in_list )
1320         inst_op_num = inst_form->operand_position(op_name, Component::USE_DEF);
1321       assert( inst_op_num != NameList::Not_in_list, "Did not find operand as USE");
1322       // find the name of the OperandForm from the local name
1323       const Form *form   = inst_form->_localNames[op_name];
1324       OperandForm  *op_form = form->is_operand();
1325       if( opnds_index == 0 ) {
1326         // Initial setup of new instruction
1327         fprintf(fp, "        // ----- Initial setup -----\n");
1328         //
1329         // Add control edge for this node
1330         fprintf(fp, "        root->add_req(_in[0]);                // control edge\n");
1331         // Add unmatched edges from root of match tree
1332         int op_base = root_form->oper_input_base(globals);
1333         for( int unmatched_edge = 1; unmatched_edge < op_base; ++unmatched_edge ) {
1334           fprintf(fp, "        root->add_req(inst%d->in(%d));        // unmatched ideal edge\n",
1335                                           inst_num, unmatched_edge);
1336         }
1337         // If new instruction captures bottom type
1338         if( root_form->captures_bottom_type(globals) ) {
1339           // Get bottom type from instruction whose result we are replacing
1340           fprintf(fp, "        root->_bottom_type = inst%d->bottom_type();\n", inst_num);
1341         }
1342         // Define result register and result operand
1343         fprintf(fp, "        ra_->add_reference(root, inst%d);\n", inst_num);
1344         fprintf(fp, "        ra_->set_oop (root, ra_->is_oop(inst%d));\n", inst_num);
1345         fprintf(fp, "        ra_->set_pair(root->_idx, ra_->get_reg_second(inst%d), ra_->get_reg_first(inst%d));\n", inst_num, inst_num);
1346         fprintf(fp, "        root->_opnds[0] = inst%d->_opnds[0]->clone(C); // result\n", inst_num);
1347         fprintf(fp, "        // ----- Done with initial setup -----\n");
1348       } else {
1349         if( (op_form == NULL) || (op_form->is_base_constant(globals) == Form::none) ) {
1350           // Do not have ideal edges for constants after matching
1351           fprintf(fp, "        for( unsigned x%d = inst%d_idx%d; x%d < inst%d_idx%d; x%d++ )\n",
1352                   inst_op_num, inst_num, inst_op_num,
1353                   inst_op_num, inst_num, inst_op_num+1, inst_op_num );
1354           fprintf(fp, "          root->add_req( inst%d->in(x%d) );\n",
1355                   inst_num, inst_op_num );
1356         } else {
1357           fprintf(fp, "        // no ideal edge for constants after matching\n");
1358         }
1359         fprintf(fp, "        root->_opnds[%d] = inst%d->_opnds[%d]->clone(C);\n",
1360                 opnds_index, inst_num, inst_op_num );
1361       }
1362       ++opnds_index;
1363     }
1364   }else {
1365     // Replacing subtree with empty-tree
1366     assert( false, "ShouldNotReachHere();");
1367   }
1368 
1369   // Return the new sub-tree
1370   fprintf(fp, "        deleted = %d;\n", max_position+1 /*zero to one based*/);
1371   fprintf(fp, "        return root;  // return new root;\n");
1372   fprintf(fp, "      }\n");
1373 }
1374 
1375 
1376 // Define the Peephole method for an instruction node
1377 void ArchDesc::definePeephole(FILE *fp, InstructForm *node) {
1378   // Generate Peephole function header
1379   fprintf(fp, "MachNode *%sNode::peephole( Block *block, int block_index, PhaseRegAlloc *ra_, int &deleted, Compile* C ) {\n", node->_ident);
1380   fprintf(fp, "  bool  matches = true;\n");
1381 
1382   // Identify the maximum instruction position,
1383   // generate temporaries that hold current instruction
1384   //
1385   //   MachNode  *inst0 = NULL;
1386   //   ...
1387   //   MachNode  *instMAX = NULL;
1388   //
1389   int max_position = 0;
1390   Peephole *peep;
1391   for( peep = node->peepholes(); peep != NULL; peep = peep->next() ) {
1392     PeepMatch *pmatch = peep->match();
1393     assert( pmatch != NULL, "fatal(), missing peepmatch rule");
1394     if( max_position < pmatch->max_position() )  max_position = pmatch->max_position();
1395   }
1396   for( int i = 0; i <= max_position; ++i ) {
1397     if( i == 0 ) {
1398       fprintf(fp, "  MachNode *inst0 = this;\n");
1399     } else {
1400       fprintf(fp, "  MachNode *inst%d = NULL;\n", i);
1401     }
1402   }
1403 
1404   // For each peephole rule in architecture description
1405   //   Construct a test for the desired instruction sub-tree
1406   //   then check the constraints
1407   //   If these match, Generate the new subtree
1408   for( peep = node->peepholes(); peep != NULL; peep = peep->next() ) {
1409     int         peephole_number = peep->peephole_number();
1410     PeepMatch      *pmatch      = peep->match();
1411     PeepConstraint *pconstraint = peep->constraints();
1412     PeepReplace    *preplace    = peep->replacement();
1413 
1414     // Root of this peephole is the current MachNode
1415     assert( true, // %%name?%% strcmp( node->_ident, pmatch->name(0) ) == 0,
1416             "root of PeepMatch does not match instruction");
1417 
1418     // Make each peephole rule individually selectable
1419     fprintf(fp, "  if( (OptoPeepholeAt == -1) || (OptoPeepholeAt==%d) ) {\n", peephole_number);
1420     fprintf(fp, "    matches = true;\n");
1421     // Scan the peepmatch and output a test for each instruction
1422     check_peepmatch_instruction_sequence( fp, pmatch, pconstraint );
1423 
1424     // Check constraints and build replacement inside scope
1425     fprintf(fp, "    // If instruction subtree matches\n");
1426     fprintf(fp, "    if( matches ) {\n");
1427 
1428     // Generate tests for the constraints
1429     check_peepconstraints( fp, _globalNames, pmatch, pconstraint );
1430 
1431     // Construct the new sub-tree
1432     generate_peepreplace( fp, _globalNames, pmatch, pconstraint, preplace, max_position );
1433 
1434     // End of scope for this peephole's constraints
1435     fprintf(fp, "    }\n");
1436     // Closing brace '}' to make each peephole rule individually selectable
1437     fprintf(fp, "  } // end of peephole rule #%d\n", peephole_number);
1438     fprintf(fp, "\n");
1439   }
1440 
1441   fprintf(fp, "  return NULL;  // No peephole rules matched\n");
1442   fprintf(fp, "}\n");
1443   fprintf(fp, "\n");
1444 }
1445 
1446 // Define the Expand method for an instruction node
1447 void ArchDesc::defineExpand(FILE *fp, InstructForm *node) {
1448   unsigned      cnt  = 0;          // Count nodes we have expand into
1449   unsigned      i;
1450 
1451   // Generate Expand function header
1452   fprintf(fp, "MachNode* %sNode::Expand(State* state, Node_List& proj_list, Node* mem) {\n", node->_ident);
1453   fprintf(fp, "  Compile* C = Compile::current();\n");
1454   // Generate expand code
1455   if( node->expands() ) {
1456     const char   *opid;
1457     int           new_pos, exp_pos;
1458     const char   *new_id   = NULL;
1459     const Form   *frm      = NULL;
1460     InstructForm *new_inst = NULL;
1461     OperandForm  *new_oper = NULL;
1462     unsigned      numo     = node->num_opnds() +
1463                                 node->_exprule->_newopers.count();
1464 
1465     // If necessary, generate any operands created in expand rule
1466     if (node->_exprule->_newopers.count()) {
1467       for(node->_exprule->_newopers.reset();
1468           (new_id = node->_exprule->_newopers.iter()) != NULL; cnt++) {
1469         frm = node->_localNames[new_id];
1470         assert(frm, "Invalid entry in new operands list of expand rule");
1471         new_oper = frm->is_operand();
1472         char *tmp = (char *)node->_exprule->_newopconst[new_id];
1473         if (tmp == NULL) {
1474           fprintf(fp,"  MachOper *op%d = new (C) %sOper();\n",
1475                   cnt, new_oper->_ident);
1476         }
1477         else {
1478           fprintf(fp,"  MachOper *op%d = new (C) %sOper(%s);\n",
1479                   cnt, new_oper->_ident, tmp);
1480         }
1481       }
1482     }
1483     cnt = 0;
1484     // Generate the temps to use for DAG building
1485     for(i = 0; i < numo; i++) {
1486       if (i < node->num_opnds()) {
1487         fprintf(fp,"  MachNode *tmp%d = this;\n", i);
1488       }
1489       else {
1490         fprintf(fp,"  MachNode *tmp%d = NULL;\n", i);
1491       }
1492     }
1493     // Build mapping from num_edges to local variables
1494     fprintf(fp,"  unsigned num0 = 0;\n");
1495     for( i = 1; i < node->num_opnds(); i++ ) {
1496       fprintf(fp,"  unsigned num%d = opnd_array(%d)->num_edges();\n",i,i);
1497     }
1498 
1499     // Build a mapping from operand index to input edges
1500     fprintf(fp,"  unsigned idx0 = oper_input_base();\n");
1501 
1502     // The order in which the memory input is added to a node is very
1503     // strange.  Store nodes get a memory input before Expand is
1504     // called and other nodes get it afterwards or before depending on
1505     // match order so oper_input_base is wrong during expansion.  This
1506     // code adjusts it so that expansion will work correctly.
1507     int has_memory_edge = node->_matrule->needs_ideal_memory_edge(_globalNames);
1508     if (has_memory_edge) {
1509       fprintf(fp,"  if (mem == (Node*)1) {\n");
1510       fprintf(fp,"    idx0--; // Adjust base because memory edge hasn't been inserted yet\n");
1511       fprintf(fp,"  }\n");
1512     }
1513 
1514     for( i = 0; i < node->num_opnds(); i++ ) {
1515       fprintf(fp,"  unsigned idx%d = idx%d + num%d;\n",
1516               i+1,i,i);
1517     }
1518 
1519     // Declare variable to hold root of expansion
1520     fprintf(fp,"  MachNode *result = NULL;\n");
1521 
1522     // Iterate over the instructions 'node' expands into
1523     ExpandRule  *expand       = node->_exprule;
1524     NameAndList *expand_instr = NULL;
1525     for(expand->reset_instructions();
1526         (expand_instr = expand->iter_instructions()) != NULL; cnt++) {
1527       new_id = expand_instr->name();
1528 
1529       InstructForm* expand_instruction = (InstructForm*)globalAD->globalNames()[new_id];
1530 
1531       if (!expand_instruction) {
1532         globalAD->syntax_err(node->_linenum, "In %s: instruction %s used in expand not declared\n",
1533                              node->_ident, new_id);
1534         continue;
1535       }
1536 
1537       if (expand_instruction->has_temps()) {
1538         globalAD->syntax_err(node->_linenum, "In %s: expand rules using instructs with TEMPs aren't supported: %s",
1539                              node->_ident, new_id);
1540       }
1541 
1542       // Build the node for the instruction
1543       fprintf(fp,"\n  %sNode *n%d = new (C) %sNode();\n", new_id, cnt, new_id);
1544       // Add control edge for this node
1545       fprintf(fp,"  n%d->add_req(_in[0]);\n", cnt);
1546       // Build the operand for the value this node defines.
1547       Form *form = (Form*)_globalNames[new_id];
1548       assert( form, "'new_id' must be a defined form name");
1549       // Grab the InstructForm for the new instruction
1550       new_inst = form->is_instruction();
1551       assert( new_inst, "'new_id' must be an instruction name");
1552       if( node->is_ideal_if() && new_inst->is_ideal_if() ) {
1553         fprintf(fp, "  ((MachIfNode*)n%d)->_prob = _prob;\n",cnt);
1554         fprintf(fp, "  ((MachIfNode*)n%d)->_fcnt = _fcnt;\n",cnt);
1555       }
1556 
1557       if( node->is_ideal_fastlock() && new_inst->is_ideal_fastlock() ) {
1558         fprintf(fp, "  ((MachFastLockNode*)n%d)->_counters = _counters;\n",cnt);
1559         fprintf(fp, "  ((MachFastLockNode*)n%d)->_rtm_counters = _rtm_counters;\n",cnt);
1560         fprintf(fp, "  ((MachFastLockNode*)n%d)->_stack_rtm_counters = _stack_rtm_counters;\n",cnt);
1561       }
1562 
1563       // Fill in the bottom_type where requested
1564       if (node->captures_bottom_type(_globalNames) &&
1565           new_inst->captures_bottom_type(_globalNames)) {
1566         fprintf(fp, "  ((MachTypeNode*)n%d)->_bottom_type = bottom_type();\n", cnt);
1567       }
1568 
1569       const char *resultOper = new_inst->reduce_result();
1570       fprintf(fp,"  n%d->set_opnd_array(0, state->MachOperGenerator( %s, C ));\n",
1571               cnt, machOperEnum(resultOper));
1572 
1573       // get the formal operand NameList
1574       NameList *formal_lst = &new_inst->_parameters;
1575       formal_lst->reset();
1576 
1577       // Handle any memory operand
1578       int memory_operand = new_inst->memory_operand(_globalNames);
1579       if( memory_operand != InstructForm::NO_MEMORY_OPERAND ) {
1580         int node_mem_op = node->memory_operand(_globalNames);
1581         assert( node_mem_op != InstructForm::NO_MEMORY_OPERAND,
1582                 "expand rule member needs memory but top-level inst doesn't have any" );
1583         if (has_memory_edge) {
1584           // Copy memory edge
1585           fprintf(fp,"  if (mem != (Node*)1) {\n");
1586           fprintf(fp,"    n%d->add_req(_in[1]);\t// Add memory edge\n", cnt);
1587           fprintf(fp,"  }\n");
1588         }
1589       }
1590 
1591       // Iterate over the new instruction's operands
1592       int prev_pos = -1;
1593       for( expand_instr->reset(); (opid = expand_instr->iter()) != NULL; ) {
1594         // Use 'parameter' at current position in list of new instruction's formals
1595         // instead of 'opid' when looking up info internal to new_inst
1596         const char *parameter = formal_lst->iter();
1597         if (!parameter) {
1598           globalAD->syntax_err(node->_linenum, "Operand %s of expand instruction %s has"
1599                                " no equivalent in new instruction %s.",
1600                                opid, node->_ident, new_inst->_ident);
1601           assert(0, "Wrong expand");
1602         }
1603 
1604         // Check for an operand which is created in the expand rule
1605         if ((exp_pos = node->_exprule->_newopers.index(opid)) != -1) {
1606           new_pos = new_inst->operand_position(parameter,Component::USE);
1607           exp_pos += node->num_opnds();
1608           // If there is no use of the created operand, just skip it
1609           if (new_pos != NameList::Not_in_list) {
1610             //Copy the operand from the original made above
1611             fprintf(fp,"  n%d->set_opnd_array(%d, op%d->clone(C)); // %s\n",
1612                     cnt, new_pos, exp_pos-node->num_opnds(), opid);
1613             // Check for who defines this operand & add edge if needed
1614             fprintf(fp,"  if(tmp%d != NULL)\n", exp_pos);
1615             fprintf(fp,"    n%d->add_req(tmp%d);\n", cnt, exp_pos);
1616           }
1617         }
1618         else {
1619           // Use operand name to get an index into instruction component list
1620           // ins = (InstructForm *) _globalNames[new_id];
1621           exp_pos = node->operand_position_format(opid);
1622           assert(exp_pos != -1, "Bad expand rule");
1623           if (prev_pos > exp_pos && expand_instruction->_matrule != NULL) {
1624             // For the add_req calls below to work correctly they need
1625             // to added in the same order that a match would add them.
1626             // This means that they would need to be in the order of
1627             // the components list instead of the formal parameters.
1628             // This is a sort of hidden invariant that previously
1629             // wasn't checked and could lead to incorrectly
1630             // constructed nodes.
1631             syntax_err(node->_linenum, "For expand in %s to work, parameter declaration order in %s must follow matchrule\n",
1632                        node->_ident, new_inst->_ident);
1633           }
1634           prev_pos = exp_pos;
1635 
1636           new_pos = new_inst->operand_position(parameter,Component::USE);
1637           if (new_pos != -1) {
1638             // Copy the operand from the ExpandNode to the new node
1639             fprintf(fp,"  n%d->set_opnd_array(%d, opnd_array(%d)->clone(C)); // %s\n",
1640                     cnt, new_pos, exp_pos, opid);
1641             // For each operand add appropriate input edges by looking at tmp's
1642             fprintf(fp,"  if(tmp%d == this) {\n", exp_pos);
1643             // Grab corresponding edges from ExpandNode and insert them here
1644             fprintf(fp,"    for(unsigned i = 0; i < num%d; i++) {\n", exp_pos);
1645             fprintf(fp,"      n%d->add_req(_in[i + idx%d]);\n", cnt, exp_pos);
1646             fprintf(fp,"    }\n");
1647             fprintf(fp,"  }\n");
1648             // This value is generated by one of the new instructions
1649             fprintf(fp,"  else n%d->add_req(tmp%d);\n", cnt, exp_pos);
1650           }
1651         }
1652 
1653         // Update the DAG tmp's for values defined by this instruction
1654         int new_def_pos = new_inst->operand_position(parameter,Component::DEF);
1655         Effect *eform = (Effect *)new_inst->_effects[parameter];
1656         // If this operand is a definition in either an effects rule
1657         // or a match rule
1658         if((eform) && (is_def(eform->_use_def))) {
1659           // Update the temp associated with this operand
1660           fprintf(fp,"  tmp%d = n%d;\n", exp_pos, cnt);
1661         }
1662         else if( new_def_pos != -1 ) {
1663           // Instruction defines a value but user did not declare it
1664           // in the 'effect' clause
1665           fprintf(fp,"  tmp%d = n%d;\n", exp_pos, cnt);
1666         }
1667       } // done iterating over a new instruction's operands
1668 
1669       // Invoke Expand() for the newly created instruction.
1670       fprintf(fp,"  result = n%d->Expand( state, proj_list, mem );\n", cnt);
1671       assert( !new_inst->expands(), "Do not have complete support for recursive expansion");
1672     } // done iterating over new instructions
1673     fprintf(fp,"\n");
1674   } // done generating expand rule
1675 
1676   // Generate projections for instruction's additional DEFs and KILLs
1677   if( ! node->expands() && (node->needs_projections() || node->has_temps())) {
1678     // Get string representing the MachNode that projections point at
1679     const char *machNode = "this";
1680     // Generate the projections
1681     fprintf(fp,"  // Add projection edges for additional defs or kills\n");
1682 
1683     // Examine each component to see if it is a DEF or KILL
1684     node->_components.reset();
1685     // Skip the first component, if already handled as (SET dst (...))
1686     Component *comp = NULL;
1687     // For kills, the choice of projection numbers is arbitrary
1688     int proj_no = 1;
1689     bool declared_def  = false;
1690     bool declared_kill = false;
1691 
1692     while( (comp = node->_components.iter()) != NULL ) {
1693       // Lookup register class associated with operand type
1694       Form        *form = (Form*)_globalNames[comp->_type];
1695       assert( form, "component type must be a defined form");
1696       OperandForm *op   = form->is_operand();
1697 
1698       if (comp->is(Component::TEMP)) {
1699         fprintf(fp, "  // TEMP %s\n", comp->_name);
1700         if (!declared_def) {
1701           // Define the variable "def" to hold new MachProjNodes
1702           fprintf(fp, "  MachTempNode *def;\n");
1703           declared_def = true;
1704         }
1705         if (op && op->_interface && op->_interface->is_RegInterface()) {
1706           fprintf(fp,"  def = new (C) MachTempNode(state->MachOperGenerator( %s, C ));\n",
1707                   machOperEnum(op->_ident));
1708           fprintf(fp,"  add_req(def);\n");
1709           // The operand for TEMP is already constructed during
1710           // this mach node construction, see buildMachNode().
1711           //
1712           // int idx  = node->operand_position_format(comp->_name);
1713           // fprintf(fp,"  set_opnd_array(%d, state->MachOperGenerator( %s, C ));\n",
1714           //         idx, machOperEnum(op->_ident));
1715         } else {
1716           assert(false, "can't have temps which aren't registers");
1717         }
1718       } else if (comp->isa(Component::KILL)) {
1719         fprintf(fp, "  // DEF/KILL %s\n", comp->_name);
1720 
1721         if (!declared_kill) {
1722           // Define the variable "kill" to hold new MachProjNodes
1723           fprintf(fp, "  MachProjNode *kill;\n");
1724           declared_kill = true;
1725         }
1726 
1727         assert( op, "Support additional KILLS for base operands");
1728         const char *regmask    = reg_mask(*op);
1729         const char *ideal_type = op->ideal_type(_globalNames, _register);
1730 
1731         if (!op->is_bound_register()) {
1732           syntax_err(node->_linenum, "In %s only bound registers can be killed: %s %s\n",
1733                      node->_ident, comp->_type, comp->_name);
1734         }
1735 
1736         fprintf(fp,"  kill = ");
1737         fprintf(fp,"new (C) MachProjNode( %s, %d, (%s), Op_%s );\n",
1738                 machNode, proj_no++, regmask, ideal_type);
1739         fprintf(fp,"  proj_list.push(kill);\n");
1740       }
1741     }
1742   }
1743 
1744   if( !node->expands() && node->_matrule != NULL ) {
1745     // Remove duplicated operands and inputs which use the same name.
1746     // Seach through match operands for the same name usage.
1747     uint cur_num_opnds = node->num_opnds();
1748     if( cur_num_opnds > 1 && cur_num_opnds != node->num_unique_opnds() ) {
1749       Component *comp = NULL;
1750       // Build mapping from num_edges to local variables
1751       fprintf(fp,"  unsigned num0 = 0;\n");
1752       for( i = 1; i < cur_num_opnds; i++ ) {
1753         fprintf(fp,"  unsigned num%d = opnd_array(%d)->num_edges();",i,i);
1754         fprintf(fp, " \t// %s\n", node->opnd_ident(i));
1755       }
1756       // Build a mapping from operand index to input edges
1757       fprintf(fp,"  unsigned idx0 = oper_input_base();\n");
1758       for( i = 0; i < cur_num_opnds; i++ ) {
1759         fprintf(fp,"  unsigned idx%d = idx%d + num%d;\n",
1760                 i+1,i,i);
1761       }
1762 
1763       uint new_num_opnds = 1;
1764       node->_components.reset();
1765       // Skip first unique operands.
1766       for( i = 1; i < cur_num_opnds; i++ ) {
1767         comp = node->_components.iter();
1768         if (i != node->unique_opnds_idx(i)) {
1769           break;
1770         }
1771         new_num_opnds++;
1772       }
1773       // Replace not unique operands with next unique operands.
1774       for( ; i < cur_num_opnds; i++ ) {
1775         comp = node->_components.iter();
1776         uint j = node->unique_opnds_idx(i);
1777         // unique_opnds_idx(i) is unique if unique_opnds_idx(j) is not unique.
1778         if( j != node->unique_opnds_idx(j) ) {
1779           fprintf(fp,"  set_opnd_array(%d, opnd_array(%d)->clone(C)); // %s\n",
1780                   new_num_opnds, i, comp->_name);
1781           // delete not unique edges here
1782           fprintf(fp,"  for(unsigned i = 0; i < num%d; i++) {\n", i);
1783           fprintf(fp,"    set_req(i + idx%d, _in[i + idx%d]);\n", new_num_opnds, i);
1784           fprintf(fp,"  }\n");
1785           fprintf(fp,"  num%d = num%d;\n", new_num_opnds, i);
1786           fprintf(fp,"  idx%d = idx%d + num%d;\n", new_num_opnds+1, new_num_opnds, new_num_opnds);
1787           new_num_opnds++;
1788         }
1789       }
1790       // delete the rest of edges
1791       fprintf(fp,"  for(int i = idx%d - 1; i >= (int)idx%d; i--) {\n", cur_num_opnds, new_num_opnds);
1792       fprintf(fp,"    del_req(i);\n");
1793       fprintf(fp,"  }\n");
1794       fprintf(fp,"  _num_opnds = %d;\n", new_num_opnds);
1795       assert(new_num_opnds == node->num_unique_opnds(), "what?");
1796     }
1797   }
1798 
1799   // If the node is a MachConstantNode, insert the MachConstantBaseNode edge.
1800   // NOTE: this edge must be the last input (see MachConstantNode::mach_constant_base_node_input).
1801   // There are nodes that don't use $constantablebase, but still require that it
1802   // is an input to the node. Example: divF_reg_immN, Repl32B_imm on x86_64.
1803   if (node->is_mach_constant() || node->needs_constant_base()) {
1804     if (node->is_ideal_call() != Form::invalid_type &&
1805         node->is_ideal_call() != Form::JAVA_LEAF) {
1806       fprintf(fp, "  // MachConstantBaseNode added in matcher.\n");
1807       _needs_clone_jvms = true;
1808     } else {
1809       fprintf(fp, "  add_req(C->mach_constant_base_node());\n");
1810     }
1811   }
1812 
1813   fprintf(fp, "\n");
1814   if (node->expands()) {
1815     fprintf(fp, "  return result;\n");
1816   } else {
1817     fprintf(fp, "  return this;\n");
1818   }
1819   fprintf(fp, "}\n");
1820   fprintf(fp, "\n");
1821 }
1822 
1823 
1824 //------------------------------Emit Routines----------------------------------
1825 // Special classes and routines for defining node emit routines which output
1826 // target specific instruction object encodings.
1827 // Define the ___Node::emit() routine
1828 //
1829 // (1) void  ___Node::emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const {
1830 // (2)   // ...  encoding defined by user
1831 // (3)
1832 // (4) }
1833 //
1834 
1835 class DefineEmitState {
1836 private:
1837   enum reloc_format { RELOC_NONE        = -1,
1838                       RELOC_IMMEDIATE   =  0,
1839                       RELOC_DISP        =  1,
1840                       RELOC_CALL_DISP   =  2 };
1841   enum literal_status{ LITERAL_NOT_SEEN  = 0,
1842                        LITERAL_SEEN      = 1,
1843                        LITERAL_ACCESSED  = 2,
1844                        LITERAL_OUTPUT    = 3 };
1845   // Temporaries that describe current operand
1846   bool          _cleared;
1847   OpClassForm  *_opclass;
1848   OperandForm  *_operand;
1849   int           _operand_idx;
1850   const char   *_local_name;
1851   const char   *_operand_name;
1852   bool          _doing_disp;
1853   bool          _doing_constant;
1854   Form::DataType _constant_type;
1855   DefineEmitState::literal_status _constant_status;
1856   DefineEmitState::literal_status _reg_status;
1857   bool          _doing_emit8;
1858   bool          _doing_emit_d32;
1859   bool          _doing_emit_d16;
1860   bool          _doing_emit_hi;
1861   bool          _doing_emit_lo;
1862   bool          _may_reloc;
1863   reloc_format  _reloc_form;
1864   const char *  _reloc_type;
1865   bool          _processing_noninput;
1866 
1867   NameList      _strings_to_emit;
1868 
1869   // Stable state, set by constructor
1870   ArchDesc     &_AD;
1871   FILE         *_fp;
1872   EncClass     &_encoding;
1873   InsEncode    &_ins_encode;
1874   InstructForm &_inst;
1875 
1876 public:
1877   DefineEmitState(FILE *fp, ArchDesc &AD, EncClass &encoding,
1878                   InsEncode &ins_encode, InstructForm &inst)
1879     : _AD(AD), _fp(fp), _encoding(encoding), _ins_encode(ins_encode), _inst(inst) {
1880       clear();
1881   }
1882 
1883   void clear() {
1884     _cleared       = true;
1885     _opclass       = NULL;
1886     _operand       = NULL;
1887     _operand_idx   = 0;
1888     _local_name    = "";
1889     _operand_name  = "";
1890     _doing_disp    = false;
1891     _doing_constant= false;
1892     _constant_type = Form::none;
1893     _constant_status = LITERAL_NOT_SEEN;
1894     _reg_status      = LITERAL_NOT_SEEN;
1895     _doing_emit8   = false;
1896     _doing_emit_d32= false;
1897     _doing_emit_d16= false;
1898     _doing_emit_hi = false;
1899     _doing_emit_lo = false;
1900     _may_reloc     = false;
1901     _reloc_form    = RELOC_NONE;
1902     _reloc_type    = AdlcVMDeps::none_reloc_type();
1903     _strings_to_emit.clear();
1904   }
1905 
1906   // Track necessary state when identifying a replacement variable
1907   // @arg rep_var: The formal parameter of the encoding.
1908   void update_state(const char *rep_var) {
1909     // A replacement variable or one of its subfields
1910     // Obtain replacement variable from list
1911     if ( (*rep_var) != '$' ) {
1912       // A replacement variable, '$' prefix
1913       // check_rep_var( rep_var );
1914       if ( Opcode::as_opcode_type(rep_var) != Opcode::NOT_AN_OPCODE ) {
1915         // No state needed.
1916         assert( _opclass == NULL,
1917                 "'primary', 'secondary' and 'tertiary' don't follow operand.");
1918       }
1919       else if ((strcmp(rep_var, "constanttablebase") == 0) ||
1920                (strcmp(rep_var, "constantoffset")    == 0) ||
1921                (strcmp(rep_var, "constantaddress")   == 0)) {
1922         if (!(_inst.is_mach_constant() || _inst.needs_constant_base())) {
1923           _AD.syntax_err(_encoding._linenum,
1924                          "Replacement variable %s not allowed in instruct %s (only in MachConstantNode or MachCall).\n",
1925                          rep_var, _encoding._name);
1926         }
1927       }
1928       else {
1929         // Lookup its position in (formal) parameter list of encoding
1930         int   param_no  = _encoding.rep_var_index(rep_var);
1931         if ( param_no == -1 ) {
1932           _AD.syntax_err( _encoding._linenum,
1933                           "Replacement variable %s not found in enc_class %s.\n",
1934                           rep_var, _encoding._name);
1935         }
1936 
1937         // Lookup the corresponding ins_encode parameter
1938         // This is the argument (actual parameter) to the encoding.
1939         const char *inst_rep_var = _ins_encode.rep_var_name(_inst, param_no);
1940         if (inst_rep_var == NULL) {
1941           _AD.syntax_err( _ins_encode._linenum,
1942                           "Parameter %s not passed to enc_class %s from instruct %s.\n",
1943                           rep_var, _encoding._name, _inst._ident);
1944         }
1945 
1946         // Check if instruction's actual parameter is a local name in the instruction
1947         const Form  *local     = _inst._localNames[inst_rep_var];
1948         OpClassForm *opc       = (local != NULL) ? local->is_opclass() : NULL;
1949         // Note: assert removed to allow constant and symbolic parameters
1950         // assert( opc, "replacement variable was not found in local names");
1951         // Lookup the index position iff the replacement variable is a localName
1952         int idx  = (opc != NULL) ? _inst.operand_position_format(inst_rep_var) : -1;
1953 
1954         if ( idx != -1 ) {
1955           // This is a local in the instruction
1956           // Update local state info.
1957           _opclass        = opc;
1958           _operand_idx    = idx;
1959           _local_name     = rep_var;
1960           _operand_name   = inst_rep_var;
1961 
1962           // !!!!!
1963           // Do not support consecutive operands.
1964           assert( _operand == NULL, "Unimplemented()");
1965           _operand = opc->is_operand();
1966         }
1967         else if( ADLParser::is_literal_constant(inst_rep_var) ) {
1968           // Instruction provided a constant expression
1969           // Check later that encoding specifies $$$constant to resolve as constant
1970           _constant_status   = LITERAL_SEEN;
1971         }
1972         else if( Opcode::as_opcode_type(inst_rep_var) != Opcode::NOT_AN_OPCODE ) {
1973           // Instruction provided an opcode: "primary", "secondary", "tertiary"
1974           // Check later that encoding specifies $$$constant to resolve as constant
1975           _constant_status   = LITERAL_SEEN;
1976         }
1977         else if((_AD.get_registers() != NULL ) && (_AD.get_registers()->getRegDef(inst_rep_var) != NULL)) {
1978           // Instruction provided a literal register name for this parameter
1979           // Check that encoding specifies $$$reg to resolve.as register.
1980           _reg_status        = LITERAL_SEEN;
1981         }
1982         else {
1983           // Check for unimplemented functionality before hard failure
1984           assert( strcmp(opc->_ident,"label")==0, "Unimplemented() Label");
1985           assert( false, "ShouldNotReachHere()");
1986         }
1987       } // done checking which operand this is.
1988     } else {
1989       //
1990       // A subfield variable, '$$' prefix
1991       // Check for fields that may require relocation information.
1992       // Then check that literal register parameters are accessed with 'reg' or 'constant'
1993       //
1994       if ( strcmp(rep_var,"$disp") == 0 ) {
1995         _doing_disp = true;
1996         assert( _opclass, "Must use operand or operand class before '$disp'");
1997         if( _operand == NULL ) {
1998           // Only have an operand class, generate run-time check for relocation
1999           _may_reloc    = true;
2000           _reloc_form   = RELOC_DISP;
2001           _reloc_type   = AdlcVMDeps::oop_reloc_type();
2002         } else {
2003           // Do precise check on operand: is it a ConP or not
2004           //
2005           // Check interface for value of displacement
2006           assert( ( _operand->_interface != NULL ),
2007                   "$disp can only follow memory interface operand");
2008           MemInterface *mem_interface= _operand->_interface->is_MemInterface();
2009           assert( mem_interface != NULL,
2010                   "$disp can only follow memory interface operand");
2011           const char *disp = mem_interface->_disp;
2012 
2013           if( disp != NULL && (*disp == '$') ) {
2014             // MemInterface::disp contains a replacement variable,
2015             // Check if this matches a ConP
2016             //
2017             // Lookup replacement variable, in operand's component list
2018             const char *rep_var_name = disp + 1; // Skip '$'
2019             const Component *comp = _operand->_components.search(rep_var_name);
2020             assert( comp != NULL,"Replacement variable not found in components");
2021             const char      *type = comp->_type;
2022             // Lookup operand form for replacement variable's type
2023             const Form *form = _AD.globalNames()[type];
2024             assert( form != NULL, "Replacement variable's type not found");
2025             OperandForm *op = form->is_operand();
2026             assert( op, "Attempting to emit a non-register or non-constant");
2027             // Check if this is a constant
2028             if (op->_matrule && op->_matrule->is_base_constant(_AD.globalNames())) {
2029               // Check which constant this name maps to: _c0, _c1, ..., _cn
2030               // const int idx = _operand.constant_position(_AD.globalNames(), comp);
2031               // assert( idx != -1, "Constant component not found in operand");
2032               Form::DataType dtype = op->is_base_constant(_AD.globalNames());
2033               if ( dtype == Form::idealP ) {
2034                 _may_reloc    = true;
2035                 // No longer true that idealP is always an oop
2036                 _reloc_form   = RELOC_DISP;
2037                 _reloc_type   = AdlcVMDeps::oop_reloc_type();
2038               }
2039             }
2040 
2041             else if( _operand->is_user_name_for_sReg() != Form::none ) {
2042               // The only non-constant allowed access to disp is an operand sRegX in a stackSlotX
2043               assert( op->ideal_to_sReg_type(type) != Form::none, "StackSlots access displacements using 'sRegs'");
2044               _may_reloc   = false;
2045             } else {
2046               assert( false, "fatal(); Only stackSlots can access a non-constant using 'disp'");
2047             }
2048           }
2049         } // finished with precise check of operand for relocation.
2050       } // finished with subfield variable
2051       else if ( strcmp(rep_var,"$constant") == 0 ) {
2052         _doing_constant = true;
2053         if ( _constant_status == LITERAL_NOT_SEEN ) {
2054           // Check operand for type of constant
2055           assert( _operand, "Must use operand before '$$constant'");
2056           Form::DataType dtype = _operand->is_base_constant(_AD.globalNames());
2057           _constant_type = dtype;
2058           if ( dtype == Form::idealP ) {
2059             _may_reloc    = true;
2060             // No longer true that idealP is always an oop
2061             // // _must_reloc   = true;
2062             _reloc_form   = RELOC_IMMEDIATE;
2063             _reloc_type   = AdlcVMDeps::oop_reloc_type();
2064           } else {
2065             // No relocation information needed
2066           }
2067         } else {
2068           // User-provided literals may not require relocation information !!!!!
2069           assert( _constant_status == LITERAL_SEEN, "Must know we are processing a user-provided literal");
2070         }
2071       }
2072       else if ( strcmp(rep_var,"$label") == 0 ) {
2073         // Calls containing labels require relocation
2074         if ( _inst.is_ideal_call() )  {
2075           _may_reloc    = true;
2076           // !!!!! !!!!!
2077           _reloc_type   = AdlcVMDeps::none_reloc_type();
2078         }
2079       }
2080 
2081       // literal register parameter must be accessed as a 'reg' field.
2082       if ( _reg_status != LITERAL_NOT_SEEN ) {
2083         assert( _reg_status == LITERAL_SEEN, "Must have seen register literal before now");
2084         if (strcmp(rep_var,"$reg") == 0 || reg_conversion(rep_var) != NULL) {
2085           _reg_status  = LITERAL_ACCESSED;
2086         } else {
2087           _AD.syntax_err(_encoding._linenum,
2088                          "Invalid access to literal register parameter '%s' in %s.\n",
2089                          rep_var, _encoding._name);
2090           assert( false, "invalid access to literal register parameter");
2091         }
2092       }
2093       // literal constant parameters must be accessed as a 'constant' field
2094       if (_constant_status != LITERAL_NOT_SEEN) {
2095         assert(_constant_status == LITERAL_SEEN, "Must have seen constant literal before now");
2096         if (strcmp(rep_var,"$constant") == 0) {
2097           _constant_status = LITERAL_ACCESSED;
2098         } else {
2099           _AD.syntax_err(_encoding._linenum,
2100                          "Invalid access to literal constant parameter '%s' in %s.\n",
2101                          rep_var, _encoding._name);
2102         }
2103       }
2104     } // end replacement and/or subfield
2105 
2106   }
2107 
2108   void add_rep_var(const char *rep_var) {
2109     // Handle subfield and replacement variables.
2110     if ( ( *rep_var == '$' ) && ( *(rep_var+1) == '$' ) ) {
2111       // Check for emit prefix, '$$emit32'
2112       assert( _cleared, "Can not nest $$$emit32");
2113       if ( strcmp(rep_var,"$$emit32") == 0 ) {
2114         _doing_emit_d32 = true;
2115       }
2116       else if ( strcmp(rep_var,"$$emit16") == 0 ) {
2117         _doing_emit_d16 = true;
2118       }
2119       else if ( strcmp(rep_var,"$$emit_hi") == 0 ) {
2120         _doing_emit_hi  = true;
2121       }
2122       else if ( strcmp(rep_var,"$$emit_lo") == 0 ) {
2123         _doing_emit_lo  = true;
2124       }
2125       else if ( strcmp(rep_var,"$$emit8") == 0 ) {
2126         _doing_emit8    = true;
2127       }
2128       else {
2129         _AD.syntax_err(_encoding._linenum, "Unsupported $$operation '%s'\n",rep_var);
2130         assert( false, "fatal();");
2131       }
2132     }
2133     else {
2134       // Update state for replacement variables
2135       update_state( rep_var );
2136       _strings_to_emit.addName(rep_var);
2137     }
2138     _cleared  = false;
2139   }
2140 
2141   void emit_replacement() {
2142     // A replacement variable or one of its subfields
2143     // Obtain replacement variable from list
2144     // const char *ec_rep_var = encoding->_rep_vars.iter();
2145     const char *rep_var;
2146     _strings_to_emit.reset();
2147     while ( (rep_var = _strings_to_emit.iter()) != NULL ) {
2148 
2149       if ( (*rep_var) == '$' ) {
2150         // A subfield variable, '$$' prefix
2151         emit_field( rep_var );
2152       } else {
2153         if (_strings_to_emit.peek() != NULL &&
2154             strcmp(_strings_to_emit.peek(), "$Address") == 0) {
2155           fprintf(_fp, "Address::make_raw(");
2156 
2157           emit_rep_var( rep_var );
2158           fprintf(_fp,"->base(ra_,this,idx%d), ", _operand_idx);
2159 
2160           _reg_status = LITERAL_ACCESSED;
2161           emit_rep_var( rep_var );
2162           fprintf(_fp,"->index(ra_,this,idx%d), ", _operand_idx);
2163 
2164           _reg_status = LITERAL_ACCESSED;
2165           emit_rep_var( rep_var );
2166           fprintf(_fp,"->scale(), ");
2167 
2168           _reg_status = LITERAL_ACCESSED;
2169           emit_rep_var( rep_var );
2170           Form::DataType stack_type = _operand ? _operand->is_user_name_for_sReg() : Form::none;
2171           if( _operand  && _operand_idx==0 && stack_type != Form::none ) {
2172             fprintf(_fp,"->disp(ra_,this,0), ");
2173           } else {
2174             fprintf(_fp,"->disp(ra_,this,idx%d), ", _operand_idx);
2175           }
2176 
2177           _reg_status = LITERAL_ACCESSED;
2178           emit_rep_var( rep_var );
2179           fprintf(_fp,"->disp_reloc())");
2180 
2181           // skip trailing $Address
2182           _strings_to_emit.iter();
2183         } else {
2184           // A replacement variable, '$' prefix
2185           const char* next = _strings_to_emit.peek();
2186           const char* next2 = _strings_to_emit.peek(2);
2187           if (next != NULL && next2 != NULL && strcmp(next2, "$Register") == 0 &&
2188               (strcmp(next, "$base") == 0 || strcmp(next, "$index") == 0)) {
2189             // handle $rev_var$$base$$Register and $rev_var$$index$$Register by
2190             // producing as_Register(opnd_array(#)->base(ra_,this,idx1)).
2191             fprintf(_fp, "as_Register(");
2192             // emit the operand reference
2193             emit_rep_var( rep_var );
2194             rep_var = _strings_to_emit.iter();
2195             assert(strcmp(rep_var, "$base") == 0 || strcmp(rep_var, "$index") == 0, "bad pattern");
2196             // handle base or index
2197             emit_field(rep_var);
2198             rep_var = _strings_to_emit.iter();
2199             assert(strcmp(rep_var, "$Register") == 0, "bad pattern");
2200             // close up the parens
2201             fprintf(_fp, ")");
2202           } else {
2203             emit_rep_var( rep_var );
2204           }
2205         }
2206       } // end replacement and/or subfield
2207     }
2208   }
2209 
2210   void emit_reloc_type(const char* type) {
2211     fprintf(_fp, "%s", type)
2212       ;
2213   }
2214 
2215 
2216   void emit() {
2217     //
2218     //   "emit_d32_reloc(" or "emit_hi_reloc" or "emit_lo_reloc"
2219     //
2220     // Emit the function name when generating an emit function
2221     if ( _doing_emit_d32 || _doing_emit_hi || _doing_emit_lo ) {
2222       const char *d32_hi_lo = _doing_emit_d32 ? "d32" : (_doing_emit_hi ? "hi" : "lo");
2223       // In general, relocatable isn't known at compiler compile time.
2224       // Check results of prior scan
2225       if ( ! _may_reloc ) {
2226         // Definitely don't need relocation information
2227         fprintf( _fp, "emit_%s(cbuf, ", d32_hi_lo );
2228         emit_replacement(); fprintf(_fp, ")");
2229       }
2230       else {
2231         // Emit RUNTIME CHECK to see if value needs relocation info
2232         // If emitting a relocatable address, use 'emit_d32_reloc'
2233         const char *disp_constant = _doing_disp ? "disp" : _doing_constant ? "constant" : "INVALID";
2234         assert( (_doing_disp || _doing_constant)
2235                 && !(_doing_disp && _doing_constant),
2236                 "Must be emitting either a displacement or a constant");
2237         fprintf(_fp,"\n");
2238         fprintf(_fp,"if ( opnd_array(%d)->%s_reloc() != relocInfo::none ) {\n",
2239                 _operand_idx, disp_constant);
2240         fprintf(_fp,"  ");
2241         fprintf(_fp,"emit_%s_reloc(cbuf, ", d32_hi_lo );
2242         emit_replacement();             fprintf(_fp,", ");
2243         fprintf(_fp,"opnd_array(%d)->%s_reloc(), ",
2244                 _operand_idx, disp_constant);
2245         fprintf(_fp, "%d", _reloc_form);fprintf(_fp, ");");
2246         fprintf(_fp,"\n");
2247         fprintf(_fp,"} else {\n");
2248         fprintf(_fp,"  emit_%s(cbuf, ", d32_hi_lo);
2249         emit_replacement(); fprintf(_fp, ");\n"); fprintf(_fp,"}");
2250       }
2251     }
2252     else if ( _doing_emit_d16 ) {
2253       // Relocation of 16-bit values is not supported
2254       fprintf(_fp,"emit_d16(cbuf, ");
2255       emit_replacement(); fprintf(_fp, ")");
2256       // No relocation done for 16-bit values
2257     }
2258     else if ( _doing_emit8 ) {
2259       // Relocation of 8-bit values is not supported
2260       fprintf(_fp,"emit_d8(cbuf, ");
2261       emit_replacement(); fprintf(_fp, ")");
2262       // No relocation done for 8-bit values
2263     }
2264     else {
2265       // Not an emit# command, just output the replacement string.
2266       emit_replacement();
2267     }
2268 
2269     // Get ready for next state collection.
2270     clear();
2271   }
2272 
2273 private:
2274 
2275   // recognizes names which represent MacroAssembler register types
2276   // and return the conversion function to build them from OptoReg
2277   const char* reg_conversion(const char* rep_var) {
2278     if (strcmp(rep_var,"$Register") == 0)      return "as_Register";
2279     if (strcmp(rep_var,"$FloatRegister") == 0) return "as_FloatRegister";
2280 #if defined(IA32) || defined(AMD64)
2281     if (strcmp(rep_var,"$XMMRegister") == 0)   return "as_XMMRegister";
2282 #endif
2283     if (strcmp(rep_var,"$CondRegister") == 0)  return "as_ConditionRegister";
2284     return NULL;
2285   }
2286 
2287   void emit_field(const char *rep_var) {
2288     const char* reg_convert = reg_conversion(rep_var);
2289 
2290     // A subfield variable, '$$subfield'
2291     if ( strcmp(rep_var, "$reg") == 0 || reg_convert != NULL) {
2292       // $reg form or the $Register MacroAssembler type conversions
2293       assert( _operand_idx != -1,
2294               "Must use this subfield after operand");
2295       if( _reg_status == LITERAL_NOT_SEEN ) {
2296         if (_processing_noninput) {
2297           const Form  *local     = _inst._localNames[_operand_name];
2298           OperandForm *oper      = local->is_operand();
2299           const RegDef* first = oper->get_RegClass()->find_first_elem();
2300           if (reg_convert != NULL) {
2301             fprintf(_fp, "%s(%s_enc)", reg_convert, first->_regname);
2302           } else {
2303             fprintf(_fp, "%s_enc", first->_regname);
2304           }
2305         } else {
2306           fprintf(_fp,"->%s(ra_,this", reg_convert != NULL ? reg_convert : "reg");
2307           // Add parameter for index position, if not result operand
2308           if( _operand_idx != 0 ) fprintf(_fp,",idx%d", _operand_idx);
2309           fprintf(_fp,")");
2310           fprintf(_fp, "/* %s */", _operand_name);
2311         }
2312       } else {
2313         assert( _reg_status == LITERAL_OUTPUT, "should have output register literal in emit_rep_var");
2314         // Register literal has already been sent to output file, nothing more needed
2315       }
2316     }
2317     else if ( strcmp(rep_var,"$base") == 0 ) {
2318       assert( _operand_idx != -1,
2319               "Must use this subfield after operand");
2320       assert( ! _may_reloc, "UnImplemented()");
2321       fprintf(_fp,"->base(ra_,this,idx%d)", _operand_idx);
2322     }
2323     else if ( strcmp(rep_var,"$index") == 0 ) {
2324       assert( _operand_idx != -1,
2325               "Must use this subfield after operand");
2326       assert( ! _may_reloc, "UnImplemented()");
2327       fprintf(_fp,"->index(ra_,this,idx%d)", _operand_idx);
2328     }
2329     else if ( strcmp(rep_var,"$scale") == 0 ) {
2330       assert( ! _may_reloc, "UnImplemented()");
2331       fprintf(_fp,"->scale()");
2332     }
2333     else if ( strcmp(rep_var,"$cmpcode") == 0 ) {
2334       assert( ! _may_reloc, "UnImplemented()");
2335       fprintf(_fp,"->ccode()");
2336     }
2337     else if ( strcmp(rep_var,"$constant") == 0 ) {
2338       if( _constant_status == LITERAL_NOT_SEEN ) {
2339         if ( _constant_type == Form::idealD ) {
2340           fprintf(_fp,"->constantD()");
2341         } else if ( _constant_type == Form::idealF ) {
2342           fprintf(_fp,"->constantF()");
2343         } else if ( _constant_type == Form::idealL ) {
2344           fprintf(_fp,"->constantL()");
2345         } else {
2346           fprintf(_fp,"->constant()");
2347         }
2348       } else {
2349         assert( _constant_status == LITERAL_OUTPUT, "should have output constant literal in emit_rep_var");
2350         // Constant literal has already been sent to output file, nothing more needed
2351       }
2352     }
2353     else if ( strcmp(rep_var,"$disp") == 0 ) {
2354       Form::DataType stack_type = _operand ? _operand->is_user_name_for_sReg() : Form::none;
2355       if( _operand  && _operand_idx==0 && stack_type != Form::none ) {
2356         fprintf(_fp,"->disp(ra_,this,0)");
2357       } else {
2358         fprintf(_fp,"->disp(ra_,this,idx%d)", _operand_idx);
2359       }
2360     }
2361     else if ( strcmp(rep_var,"$label") == 0 ) {
2362       fprintf(_fp,"->label()");
2363     }
2364     else if ( strcmp(rep_var,"$method") == 0 ) {
2365       fprintf(_fp,"->method()");
2366     }
2367     else {
2368       printf("emit_field: %s\n",rep_var);
2369       globalAD->syntax_err(_inst._linenum, "Unknown replacement variable %s in format statement of %s.",
2370                            rep_var, _inst._ident);
2371       assert( false, "UnImplemented()");
2372     }
2373   }
2374 
2375 
2376   void emit_rep_var(const char *rep_var) {
2377     _processing_noninput = false;
2378     // A replacement variable, originally '$'
2379     if ( Opcode::as_opcode_type(rep_var) != Opcode::NOT_AN_OPCODE ) {
2380       if (!_inst._opcode->print_opcode(_fp, Opcode::as_opcode_type(rep_var) )) {
2381         // Missing opcode
2382         _AD.syntax_err( _inst._linenum,
2383                         "Missing $%s opcode definition in %s, used by encoding %s\n",
2384                         rep_var, _inst._ident, _encoding._name);
2385       }
2386     }
2387     else if (strcmp(rep_var, "constanttablebase") == 0) {
2388       fprintf(_fp, "as_Register(ra_->get_encode(in(mach_constant_base_node_input())))");
2389     }
2390     else if (strcmp(rep_var, "constantoffset") == 0) {
2391       fprintf(_fp, "constant_offset()");
2392     }
2393     else if (strcmp(rep_var, "constantaddress") == 0) {
2394       fprintf(_fp, "InternalAddress(__ code()->consts()->start() + constant_offset())");
2395     }
2396     else {
2397       // Lookup its position in parameter list
2398       int   param_no  = _encoding.rep_var_index(rep_var);
2399       if ( param_no == -1 ) {
2400         _AD.syntax_err( _encoding._linenum,
2401                         "Replacement variable %s not found in enc_class %s.\n",
2402                         rep_var, _encoding._name);
2403       }
2404       // Lookup the corresponding ins_encode parameter
2405       const char *inst_rep_var = _ins_encode.rep_var_name(_inst, param_no);
2406 
2407       // Check if instruction's actual parameter is a local name in the instruction
2408       const Form  *local     = _inst._localNames[inst_rep_var];
2409       OpClassForm *opc       = (local != NULL) ? local->is_opclass() : NULL;
2410       // Note: assert removed to allow constant and symbolic parameters
2411       // assert( opc, "replacement variable was not found in local names");
2412       // Lookup the index position iff the replacement variable is a localName
2413       int idx  = (opc != NULL) ? _inst.operand_position_format(inst_rep_var) : -1;
2414       if( idx != -1 ) {
2415         if (_inst.is_noninput_operand(idx)) {
2416           // This operand isn't a normal input so printing it is done
2417           // specially.
2418           _processing_noninput = true;
2419         } else {
2420           // Output the emit code for this operand
2421           fprintf(_fp,"opnd_array(%d)",idx);
2422         }
2423         assert( _operand == opc->is_operand(),
2424                 "Previous emit $operand does not match current");
2425       }
2426       else if( ADLParser::is_literal_constant(inst_rep_var) ) {
2427         // else check if it is a constant expression
2428         // Removed following assert to allow primitive C types as arguments to encodings
2429         // assert( _constant_status == LITERAL_ACCESSED, "Must be processing a literal constant parameter");
2430         fprintf(_fp,"(%s)", inst_rep_var);
2431         _constant_status = LITERAL_OUTPUT;
2432       }
2433       else if( Opcode::as_opcode_type(inst_rep_var) != Opcode::NOT_AN_OPCODE ) {
2434         // else check if "primary", "secondary", "tertiary"
2435         assert( _constant_status == LITERAL_ACCESSED, "Must be processing a literal constant parameter");
2436         if (!_inst._opcode->print_opcode(_fp, Opcode::as_opcode_type(inst_rep_var) )) {
2437           // Missing opcode
2438           _AD.syntax_err( _inst._linenum,
2439                           "Missing $%s opcode definition in %s\n",
2440                           rep_var, _inst._ident);
2441 
2442         }
2443         _constant_status = LITERAL_OUTPUT;
2444       }
2445       else if((_AD.get_registers() != NULL ) && (_AD.get_registers()->getRegDef(inst_rep_var) != NULL)) {
2446         // Instruction provided a literal register name for this parameter
2447         // Check that encoding specifies $$$reg to resolve.as register.
2448         assert( _reg_status == LITERAL_ACCESSED, "Must be processing a literal register parameter");
2449         fprintf(_fp,"(%s_enc)", inst_rep_var);
2450         _reg_status = LITERAL_OUTPUT;
2451       }
2452       else {
2453         // Check for unimplemented functionality before hard failure
2454         assert( strcmp(opc->_ident,"label")==0, "Unimplemented() Label");
2455         assert( false, "ShouldNotReachHere()");
2456       }
2457       // all done
2458     }
2459   }
2460 
2461 };  // end class DefineEmitState
2462 
2463 
2464 void ArchDesc::defineSize(FILE *fp, InstructForm &inst) {
2465 
2466   //(1)
2467   // Output instruction's emit prototype
2468   fprintf(fp,"uint %sNode::size(PhaseRegAlloc *ra_) const {\n",
2469           inst._ident);
2470 
2471   fprintf(fp, "  assert(VerifyOops || MachNode::size(ra_) <= %s, \"bad fixed size\");\n", inst._size);
2472 
2473   //(2)
2474   // Print the size
2475   fprintf(fp, "  return (VerifyOops ? MachNode::size(ra_) : %s);\n", inst._size);
2476 
2477   // (3) and (4)
2478   fprintf(fp,"}\n\n");
2479 }
2480 
2481 // Emit postalloc expand function.
2482 void ArchDesc::define_postalloc_expand(FILE *fp, InstructForm &inst) {
2483   InsEncode *ins_encode = inst._insencode;
2484 
2485   // Output instruction's postalloc_expand prototype.
2486   fprintf(fp, "void  %sNode::postalloc_expand(GrowableArray <Node *> *nodes, PhaseRegAlloc *ra_) {\n",
2487           inst._ident);
2488 
2489   assert((_encode != NULL) && (ins_encode != NULL), "You must define an encode section.");
2490 
2491   // Output each operand's offset into the array of registers.
2492   inst.index_temps(fp, _globalNames);
2493 
2494   // Output variables "unsigned idx_<par_name>", Node *n_<par_name> and "MachOpnd *op_<par_name>"
2495   // for each parameter <par_name> specified in the encoding.
2496   ins_encode->reset();
2497   const char *ec_name = ins_encode->encode_class_iter();
2498   assert(ec_name != NULL, "Postalloc expand must specify an encoding.");
2499 
2500   EncClass *encoding = _encode->encClass(ec_name);
2501   if (encoding == NULL) {
2502     fprintf(stderr, "User did not define contents of this encode_class: %s\n", ec_name);
2503     abort();
2504   }
2505   if (ins_encode->current_encoding_num_args() != encoding->num_args()) {
2506     globalAD->syntax_err(ins_encode->_linenum, "In %s: passing %d arguments to %s but expecting %d",
2507                          inst._ident, ins_encode->current_encoding_num_args(),
2508                          ec_name, encoding->num_args());
2509   }
2510 
2511   fprintf(fp, "  // Access to ins and operands for postalloc expand.\n");
2512   const int buflen = 2000;
2513   char idxbuf[buflen]; char *ib = idxbuf; idxbuf[0] = '\0';
2514   char nbuf  [buflen]; char *nb = nbuf;   nbuf[0]   = '\0';
2515   char opbuf [buflen]; char *ob = opbuf;  opbuf[0]  = '\0';
2516 
2517   encoding->_parameter_type.reset();
2518   encoding->_parameter_name.reset();
2519   const char *type = encoding->_parameter_type.iter();
2520   const char *name = encoding->_parameter_name.iter();
2521   int param_no = 0;
2522   for (; (type != NULL) && (name != NULL);
2523        (type = encoding->_parameter_type.iter()), (name = encoding->_parameter_name.iter())) {
2524     const char* arg_name = ins_encode->rep_var_name(inst, param_no);
2525     int idx = inst.operand_position_format(arg_name);
2526     if (strcmp(arg_name, "constanttablebase") == 0) {
2527       ib += sprintf(ib, "  unsigned idx_%-5s = mach_constant_base_node_input(); \t// %s, \t%s\n",
2528                     name, type, arg_name);
2529       nb += sprintf(nb, "  Node    *n_%-7s = lookup(idx_%s);\n", name, name);
2530       // There is no operand for the constanttablebase.
2531     } else if (inst.is_noninput_operand(idx)) {
2532       globalAD->syntax_err(inst._linenum,
2533                            "In %s: you can not pass the non-input %s to a postalloc expand encoding.\n",
2534                            inst._ident, arg_name);
2535     } else {
2536       ib += sprintf(ib, "  unsigned idx_%-5s = idx%d; \t// %s, \t%s\n",
2537                     name, idx, type, arg_name);
2538       nb += sprintf(nb, "  Node    *n_%-7s = lookup(idx_%s);\n", name, name);
2539       ob += sprintf(ob, "  %sOper *op_%s = (%sOper *)opnd_array(%d);\n", type, name, type, idx);
2540     }
2541     param_no++;
2542   }
2543   assert(ib < &idxbuf[buflen-1] && nb < &nbuf[buflen-1] && ob < &opbuf[buflen-1], "buffer overflow");
2544 
2545   fprintf(fp, "%s", idxbuf);
2546   fprintf(fp, "  Node    *n_region  = lookup(0);\n");
2547   fprintf(fp, "%s%s", nbuf, opbuf);
2548   fprintf(fp, "  Compile *C = ra_->C;\n");
2549 
2550   // Output this instruction's encodings.
2551   fprintf(fp, "  {");
2552   const char *ec_code    = NULL;
2553   const char *ec_rep_var = NULL;
2554   assert(encoding == _encode->encClass(ec_name), "");
2555 
2556   DefineEmitState pending(fp, *this, *encoding, *ins_encode, inst);
2557   encoding->_code.reset();
2558   encoding->_rep_vars.reset();
2559   // Process list of user-defined strings,
2560   // and occurrences of replacement variables.
2561   // Replacement Vars are pushed into a list and then output.
2562   while ((ec_code = encoding->_code.iter()) != NULL) {
2563     if (! encoding->_code.is_signal(ec_code)) {
2564       // Emit pending code.
2565       pending.emit();
2566       pending.clear();
2567       // Emit this code section.
2568       fprintf(fp, "%s", ec_code);
2569     } else {
2570       // A replacement variable or one of its subfields.
2571       // Obtain replacement variable from list.
2572       ec_rep_var = encoding->_rep_vars.iter();
2573       pending.add_rep_var(ec_rep_var);
2574     }
2575   }
2576   // Emit pending code.
2577   pending.emit();
2578   pending.clear();
2579   fprintf(fp, "  }\n");
2580 
2581   fprintf(fp, "}\n\n");
2582 
2583   ec_name = ins_encode->encode_class_iter();
2584   assert(ec_name == NULL, "Postalloc expand may only have one encoding.");
2585 }
2586 
2587 // defineEmit -----------------------------------------------------------------
2588 void ArchDesc::defineEmit(FILE* fp, InstructForm& inst) {
2589   InsEncode* encode = inst._insencode;
2590 
2591   // (1)
2592   // Output instruction's emit prototype
2593   fprintf(fp, "void %sNode::emit(CodeBuffer& cbuf, PhaseRegAlloc* ra_) const {\n", inst._ident);
2594 
2595   // If user did not define an encode section,
2596   // provide stub that does not generate any machine code.
2597   if( (_encode == NULL) || (encode == NULL) ) {
2598     fprintf(fp, "  // User did not define an encode section.\n");
2599     fprintf(fp, "}\n");
2600     return;
2601   }
2602 
2603   // Save current instruction's starting address (helps with relocation).
2604   fprintf(fp, "  cbuf.set_insts_mark();\n");
2605 
2606   // For MachConstantNodes which are ideal jump nodes, fill the jump table.
2607   if (inst.is_mach_constant() && inst.is_ideal_jump()) {
2608     fprintf(fp, "  ra_->C->constant_table().fill_jump_table(cbuf, (MachConstantNode*) this, _index2label);\n");
2609   }
2610 
2611   // Output each operand's offset into the array of registers.
2612   inst.index_temps(fp, _globalNames);
2613 
2614   // Output this instruction's encodings
2615   const char *ec_name;
2616   bool        user_defined = false;
2617   encode->reset();
2618   while ((ec_name = encode->encode_class_iter()) != NULL) {
2619     fprintf(fp, "  {\n");
2620     // Output user-defined encoding
2621     user_defined           = true;
2622 
2623     const char *ec_code    = NULL;
2624     const char *ec_rep_var = NULL;
2625     EncClass   *encoding   = _encode->encClass(ec_name);
2626     if (encoding == NULL) {
2627       fprintf(stderr, "User did not define contents of this encode_class: %s\n", ec_name);
2628       abort();
2629     }
2630 
2631     if (encode->current_encoding_num_args() != encoding->num_args()) {
2632       globalAD->syntax_err(encode->_linenum, "In %s: passing %d arguments to %s but expecting %d",
2633                            inst._ident, encode->current_encoding_num_args(),
2634                            ec_name, encoding->num_args());
2635     }
2636 
2637     DefineEmitState pending(fp, *this, *encoding, *encode, inst);
2638     encoding->_code.reset();
2639     encoding->_rep_vars.reset();
2640     // Process list of user-defined strings,
2641     // and occurrences of replacement variables.
2642     // Replacement Vars are pushed into a list and then output
2643     while ((ec_code = encoding->_code.iter()) != NULL) {
2644       if (!encoding->_code.is_signal(ec_code)) {
2645         // Emit pending code
2646         pending.emit();
2647         pending.clear();
2648         // Emit this code section
2649         fprintf(fp, "%s", ec_code);
2650       } else {
2651         // A replacement variable or one of its subfields
2652         // Obtain replacement variable from list
2653         ec_rep_var  = encoding->_rep_vars.iter();
2654         pending.add_rep_var(ec_rep_var);
2655       }
2656     }
2657     // Emit pending code
2658     pending.emit();
2659     pending.clear();
2660     fprintf(fp, "  }\n");
2661   } // end while instruction's encodings
2662 
2663   // Check if user stated which encoding to user
2664   if ( user_defined == false ) {
2665     fprintf(fp, "  // User did not define which encode class to use.\n");
2666   }
2667 
2668   // (3) and (4)
2669   fprintf(fp, "}\n\n");
2670 }
2671 
2672 // defineEvalConstant ---------------------------------------------------------
2673 void ArchDesc::defineEvalConstant(FILE* fp, InstructForm& inst) {
2674   InsEncode* encode = inst._constant;
2675 
2676   // (1)
2677   // Output instruction's emit prototype
2678   fprintf(fp, "void %sNode::eval_constant(Compile* C) {\n", inst._ident);
2679 
2680   // For ideal jump nodes, add a jump-table entry.
2681   if (inst.is_ideal_jump()) {
2682     fprintf(fp, "  _constant = C->constant_table().add_jump_table(this);\n");
2683   }
2684 
2685   // If user did not define an encode section,
2686   // provide stub that does not generate any machine code.
2687   if ((_encode == NULL) || (encode == NULL)) {
2688     fprintf(fp, "  // User did not define an encode section.\n");
2689     fprintf(fp, "}\n");
2690     return;
2691   }
2692 
2693   // Output this instruction's encodings
2694   const char *ec_name;
2695   bool        user_defined = false;
2696   encode->reset();
2697   while ((ec_name = encode->encode_class_iter()) != NULL) {
2698     fprintf(fp, "  {\n");
2699     // Output user-defined encoding
2700     user_defined           = true;
2701 
2702     const char *ec_code    = NULL;
2703     const char *ec_rep_var = NULL;
2704     EncClass   *encoding   = _encode->encClass(ec_name);
2705     if (encoding == NULL) {
2706       fprintf(stderr, "User did not define contents of this encode_class: %s\n", ec_name);
2707       abort();
2708     }
2709 
2710     if (encode->current_encoding_num_args() != encoding->num_args()) {
2711       globalAD->syntax_err(encode->_linenum, "In %s: passing %d arguments to %s but expecting %d",
2712                            inst._ident, encode->current_encoding_num_args(),
2713                            ec_name, encoding->num_args());
2714     }
2715 
2716     DefineEmitState pending(fp, *this, *encoding, *encode, inst);
2717     encoding->_code.reset();
2718     encoding->_rep_vars.reset();
2719     // Process list of user-defined strings,
2720     // and occurrences of replacement variables.
2721     // Replacement Vars are pushed into a list and then output
2722     while ((ec_code = encoding->_code.iter()) != NULL) {
2723       if (!encoding->_code.is_signal(ec_code)) {
2724         // Emit pending code
2725         pending.emit();
2726         pending.clear();
2727         // Emit this code section
2728         fprintf(fp, "%s", ec_code);
2729       } else {
2730         // A replacement variable or one of its subfields
2731         // Obtain replacement variable from list
2732         ec_rep_var  = encoding->_rep_vars.iter();
2733         pending.add_rep_var(ec_rep_var);
2734       }
2735     }
2736     // Emit pending code
2737     pending.emit();
2738     pending.clear();
2739     fprintf(fp, "  }\n");
2740   } // end while instruction's encodings
2741 
2742   // Check if user stated which encoding to user
2743   if (user_defined == false) {
2744     fprintf(fp, "  // User did not define which encode class to use.\n");
2745   }
2746 
2747   // (3) and (4)
2748   fprintf(fp, "}\n");
2749 }
2750 
2751 // ---------------------------------------------------------------------------
2752 //--------Utilities to build MachOper and MachNode derived Classes------------
2753 // ---------------------------------------------------------------------------
2754 
2755 //------------------------------Utilities to build Operand Classes------------
2756 static void defineIn_RegMask(FILE *fp, FormDict &globals, OperandForm &oper) {
2757   uint num_edges = oper.num_edges(globals);
2758   if( num_edges != 0 ) {
2759     // Method header
2760     fprintf(fp, "const RegMask *%sOper::in_RegMask(int index) const {\n",
2761             oper._ident);
2762 
2763     // Assert that the index is in range.
2764     fprintf(fp, "  assert(0 <= index && index < %d, \"index out of range\");\n",
2765             num_edges);
2766 
2767     // Figure out if all RegMasks are the same.
2768     const char* first_reg_class = oper.in_reg_class(0, globals);
2769     bool all_same = true;
2770     assert(first_reg_class != NULL, "did not find register mask");
2771 
2772     for (uint index = 1; all_same && index < num_edges; index++) {
2773       const char* some_reg_class = oper.in_reg_class(index, globals);
2774       assert(some_reg_class != NULL, "did not find register mask");
2775       if (strcmp(first_reg_class, some_reg_class) != 0) {
2776         all_same = false;
2777       }
2778     }
2779 
2780     if (all_same) {
2781       // Return the sole RegMask.
2782       if (strcmp(first_reg_class, "stack_slots") == 0) {
2783         fprintf(fp,"  return &(Compile::current()->FIRST_STACK_mask());\n");
2784       } else {
2785         const char* first_reg_class_to_upper = toUpper(first_reg_class);
2786         fprintf(fp,"  return &%s_mask();\n", first_reg_class_to_upper);
2787         delete[] first_reg_class_to_upper;
2788       }
2789     } else {
2790       // Build a switch statement to return the desired mask.
2791       fprintf(fp,"  switch (index) {\n");
2792 
2793       for (uint index = 0; index < num_edges; index++) {
2794         const char *reg_class = oper.in_reg_class(index, globals);
2795         assert(reg_class != NULL, "did not find register mask");
2796         if( !strcmp(reg_class, "stack_slots") ) {
2797           fprintf(fp, "  case %d: return &(Compile::current()->FIRST_STACK_mask());\n", index);
2798         } else {
2799           const char* reg_class_to_upper = toUpper(reg_class);
2800           fprintf(fp, "  case %d: return &%s_mask();\n", index, reg_class_to_upper);
2801           delete[] reg_class_to_upper;
2802         }
2803       }
2804       fprintf(fp,"  }\n");
2805       fprintf(fp,"  ShouldNotReachHere();\n");
2806       fprintf(fp,"  return NULL;\n");
2807     }
2808 
2809     // Method close
2810     fprintf(fp, "}\n\n");
2811   }
2812 }
2813 
2814 // generate code to create a clone for a class derived from MachOper
2815 //
2816 // (0)  MachOper  *MachOperXOper::clone(Compile* C) const {
2817 // (1)    return new (C) MachXOper( _ccode, _c0, _c1, ..., _cn);
2818 // (2)  }
2819 //
2820 static void defineClone(FILE *fp, FormDict &globalNames, OperandForm &oper) {
2821   fprintf(fp,"MachOper *%sOper::clone(Compile* C) const {\n", oper._ident);
2822   // Check for constants that need to be copied over
2823   const int  num_consts    = oper.num_consts(globalNames);
2824   const bool is_ideal_bool = oper.is_ideal_bool();
2825   if( (num_consts > 0) ) {
2826     fprintf(fp,"  return new (C) %sOper(", oper._ident);
2827     // generate parameters for constants
2828     int i = 0;
2829     fprintf(fp,"_c%d", i);
2830     for( i = 1; i < num_consts; ++i) {
2831       fprintf(fp,", _c%d", i);
2832     }
2833     // finish line (1)
2834     fprintf(fp,");\n");
2835   }
2836   else {
2837     assert( num_consts == 0, "Currently support zero or one constant per operand clone function");
2838     fprintf(fp,"  return new (C) %sOper();\n", oper._ident);
2839   }
2840   // finish method
2841   fprintf(fp,"}\n");
2842 }
2843 
2844 // Helper functions for bug 4796752, abstracted with minimal modification
2845 // from define_oper_interface()
2846 OperandForm *rep_var_to_operand(const char *encoding, OperandForm &oper, FormDict &globals) {
2847   OperandForm *op = NULL;
2848   // Check for replacement variable
2849   if( *encoding == '$' ) {
2850     // Replacement variable
2851     const char *rep_var = encoding + 1;
2852     // Lookup replacement variable, rep_var, in operand's component list
2853     const Component *comp = oper._components.search(rep_var);
2854     assert( comp != NULL, "Replacement variable not found in components");
2855     // Lookup operand form for replacement variable's type
2856     const char      *type = comp->_type;
2857     Form            *form = (Form*)globals[type];
2858     assert( form != NULL, "Replacement variable's type not found");
2859     op = form->is_operand();
2860     assert( op, "Attempting to emit a non-register or non-constant");
2861   }
2862 
2863   return op;
2864 }
2865 
2866 int rep_var_to_constant_index(const char *encoding, OperandForm &oper, FormDict &globals) {
2867   int idx = -1;
2868   // Check for replacement variable
2869   if( *encoding == '$' ) {
2870     // Replacement variable
2871     const char *rep_var = encoding + 1;
2872     // Lookup replacement variable, rep_var, in operand's component list
2873     const Component *comp = oper._components.search(rep_var);
2874     assert( comp != NULL, "Replacement variable not found in components");
2875     // Lookup operand form for replacement variable's type
2876     const char      *type = comp->_type;
2877     Form            *form = (Form*)globals[type];
2878     assert( form != NULL, "Replacement variable's type not found");
2879     OperandForm *op = form->is_operand();
2880     assert( op, "Attempting to emit a non-register or non-constant");
2881     // Check that this is a constant and find constant's index:
2882     if (op->_matrule && op->_matrule->is_base_constant(globals)) {
2883       idx  = oper.constant_position(globals, comp);
2884     }
2885   }
2886 
2887   return idx;
2888 }
2889 
2890 bool is_regI(const char *encoding, OperandForm &oper, FormDict &globals ) {
2891   bool is_regI = false;
2892 
2893   OperandForm *op = rep_var_to_operand(encoding, oper, globals);
2894   if( op != NULL ) {
2895     // Check that this is a register
2896     if ( (op->_matrule && op->_matrule->is_base_register(globals)) ) {
2897       // Register
2898       const char* ideal  = op->ideal_type(globals);
2899       is_regI = (ideal && (op->ideal_to_Reg_type(ideal) == Form::idealI));
2900     }
2901   }
2902 
2903   return is_regI;
2904 }
2905 
2906 bool is_conP(const char *encoding, OperandForm &oper, FormDict &globals ) {
2907   bool is_conP = false;
2908 
2909   OperandForm *op = rep_var_to_operand(encoding, oper, globals);
2910   if( op != NULL ) {
2911     // Check that this is a constant pointer
2912     if (op->_matrule && op->_matrule->is_base_constant(globals)) {
2913       // Constant
2914       Form::DataType dtype = op->is_base_constant(globals);
2915       is_conP = (dtype == Form::idealP);
2916     }
2917   }
2918 
2919   return is_conP;
2920 }
2921 
2922 
2923 // Define a MachOper interface methods
2924 void ArchDesc::define_oper_interface(FILE *fp, OperandForm &oper, FormDict &globals,
2925                                      const char *name, const char *encoding) {
2926   bool emit_position = false;
2927   int position = -1;
2928 
2929   fprintf(fp,"  virtual int            %s", name);
2930   // Generate access method for base, index, scale, disp, ...
2931   if( (strcmp(name,"base") == 0) || (strcmp(name,"index") == 0) ) {
2932     fprintf(fp,"(PhaseRegAlloc *ra_, const Node *node, int idx) const { \n");
2933     emit_position = true;
2934   } else if ( (strcmp(name,"disp") == 0) ) {
2935     fprintf(fp,"(PhaseRegAlloc *ra_, const Node *node, int idx) const { \n");
2936   } else {
2937     fprintf(fp, "() const {\n");
2938   }
2939 
2940   // Check for hexadecimal value OR replacement variable
2941   if( *encoding == '$' ) {
2942     // Replacement variable
2943     const char *rep_var = encoding + 1;
2944     fprintf(fp,"    // Replacement variable: %s\n", encoding+1);
2945     // Lookup replacement variable, rep_var, in operand's component list
2946     const Component *comp = oper._components.search(rep_var);
2947     assert( comp != NULL, "Replacement variable not found in components");
2948     // Lookup operand form for replacement variable's type
2949     const char      *type = comp->_type;
2950     Form            *form = (Form*)globals[type];
2951     assert( form != NULL, "Replacement variable's type not found");
2952     OperandForm *op = form->is_operand();
2953     assert( op, "Attempting to emit a non-register or non-constant");
2954     // Check that this is a register or a constant and generate code:
2955     if ( (op->_matrule && op->_matrule->is_base_register(globals)) ) {
2956       // Register
2957       int idx_offset = oper.register_position( globals, rep_var);
2958       position = idx_offset;
2959       fprintf(fp,"    return (int)ra_->get_encode(node->in(idx");
2960       if ( idx_offset > 0 ) fprintf(fp,                      "+%d",idx_offset);
2961       fprintf(fp,"));\n");
2962     } else if ( op->ideal_to_sReg_type(op->_ident) != Form::none ) {
2963       // StackSlot for an sReg comes either from input node or from self, when idx==0
2964       fprintf(fp,"    if( idx != 0 ) {\n");
2965       fprintf(fp,"      // Access stack offset (register number) for input operand\n");
2966       fprintf(fp,"      return ra_->reg2offset(ra_->get_reg_first(node->in(idx)));/* sReg */\n");
2967       fprintf(fp,"    }\n");
2968       fprintf(fp,"    // Access stack offset (register number) from myself\n");
2969       fprintf(fp,"    return ra_->reg2offset(ra_->get_reg_first(node));/* sReg */\n");
2970     } else if (op->_matrule && op->_matrule->is_base_constant(globals)) {
2971       // Constant
2972       // Check which constant this name maps to: _c0, _c1, ..., _cn
2973       const int idx = oper.constant_position(globals, comp);
2974       assert( idx != -1, "Constant component not found in operand");
2975       // Output code for this constant, type dependent.
2976       fprintf(fp,"    return (int)" );
2977       oper.access_constant(fp, globals, (uint)idx /* , const_type */);
2978       fprintf(fp,";\n");
2979     } else {
2980       assert( false, "Attempting to emit a non-register or non-constant");
2981     }
2982   }
2983   else if( *encoding == '0' && *(encoding+1) == 'x' ) {
2984     // Hex value
2985     fprintf(fp,"    return %s;\n", encoding);
2986   } else {
2987     globalAD->syntax_err(oper._linenum, "In operand %s: Do not support this encode constant: '%s' for %s.",
2988                          oper._ident, encoding, name);
2989     assert( false, "Do not support octal or decimal encode constants");
2990   }
2991   fprintf(fp,"  }\n");
2992 
2993   if( emit_position && (position != -1) && (oper.num_edges(globals) > 0) ) {
2994     fprintf(fp,"  virtual int            %s_position() const { return %d; }\n", name, position);
2995     MemInterface *mem_interface = oper._interface->is_MemInterface();
2996     const char *base = mem_interface->_base;
2997     const char *disp = mem_interface->_disp;
2998     if( emit_position && (strcmp(name,"base") == 0)
2999         && base != NULL && is_regI(base, oper, globals)
3000         && disp != NULL && is_conP(disp, oper, globals) ) {
3001       // Found a memory access using a constant pointer for a displacement
3002       // and a base register containing an integer offset.
3003       // In this case the base and disp are reversed with respect to what
3004       // is expected by MachNode::get_base_and_disp() and MachNode::adr_type().
3005       // Provide a non-NULL return for disp_as_type() that will allow adr_type()
3006       // to correctly compute the access type for alias analysis.
3007       //
3008       // See BugId 4796752, operand indOffset32X in i486.ad
3009       int idx = rep_var_to_constant_index(disp, oper, globals);
3010       fprintf(fp,"  virtual const TypePtr *disp_as_type() const { return _c%d; }\n", idx);
3011     }
3012   }
3013 }
3014 
3015 //
3016 // Construct the method to copy _idx, inputs and operands to new node.
3017 static void define_fill_new_machnode(bool used, FILE *fp_cpp) {
3018   fprintf(fp_cpp, "\n");
3019   fprintf(fp_cpp, "// Copy _idx, inputs and operands to new node\n");
3020   fprintf(fp_cpp, "void MachNode::fill_new_machnode( MachNode* node, Compile* C) const {\n");
3021   if( !used ) {
3022     fprintf(fp_cpp, "  // This architecture does not have cisc or short branch instructions\n");
3023     fprintf(fp_cpp, "  ShouldNotCallThis();\n");
3024     fprintf(fp_cpp, "}\n");
3025   } else {
3026     // New node must use same node index for access through allocator's tables
3027     fprintf(fp_cpp, "  // New node must use same node index\n");
3028     fprintf(fp_cpp, "  node->set_idx( _idx );\n");
3029     // Copy machine-independent inputs
3030     fprintf(fp_cpp, "  // Copy machine-independent inputs\n");
3031     fprintf(fp_cpp, "  for( uint j = 0; j < req(); j++ ) {\n");
3032     fprintf(fp_cpp, "    node->add_req(in(j));\n");
3033     fprintf(fp_cpp, "  }\n");
3034     // Copy machine operands to new MachNode
3035     fprintf(fp_cpp, "  // Copy my operands, except for cisc position\n");
3036     fprintf(fp_cpp, "  int nopnds = num_opnds();\n");
3037     fprintf(fp_cpp, "  assert( node->num_opnds() == (uint)nopnds, \"Must have same number of operands\");\n");
3038     fprintf(fp_cpp, "  MachOper **to = node->_opnds;\n");
3039     fprintf(fp_cpp, "  for( int i = 0; i < nopnds; i++ ) {\n");
3040     fprintf(fp_cpp, "    if( i != cisc_operand() ) \n");
3041     fprintf(fp_cpp, "      to[i] = _opnds[i]->clone(C);\n");
3042     fprintf(fp_cpp, "  }\n");
3043     fprintf(fp_cpp, "}\n");
3044   }
3045   fprintf(fp_cpp, "\n");
3046 }
3047 
3048 //------------------------------defineClasses----------------------------------
3049 // Define members of MachNode and MachOper classes based on
3050 // operand and instruction lists
3051 void ArchDesc::defineClasses(FILE *fp) {
3052 
3053   // Define the contents of an array containing the machine register names
3054   defineRegNames(fp, _register);
3055   // Define an array containing the machine register encoding values
3056   defineRegEncodes(fp, _register);
3057   // Generate an enumeration of user-defined register classes
3058   // and a list of register masks, one for each class.
3059   // Only define the RegMask value objects in the expand file.
3060   // Declare each as an extern const RegMask ...; in ad_<arch>.hpp
3061   declare_register_masks(_HPP_file._fp);
3062   // build_register_masks(fp);
3063   build_register_masks(_CPP_EXPAND_file._fp);
3064   // Define the pipe_classes
3065   build_pipe_classes(_CPP_PIPELINE_file._fp);
3066 
3067   // Generate Machine Classes for each operand defined in AD file
3068   fprintf(fp,"\n");
3069   fprintf(fp,"\n");
3070   fprintf(fp,"//------------------Define classes derived from MachOper---------------------\n");
3071   // Iterate through all operands
3072   _operands.reset();
3073   OperandForm *oper;
3074   for( ; (oper = (OperandForm*)_operands.iter()) != NULL; ) {
3075     // Ensure this is a machine-world instruction
3076     if ( oper->ideal_only() ) continue;
3077     // !!!!!
3078     // The declaration of labelOper is in machine-independent file: machnode
3079     if ( strcmp(oper->_ident,"label") == 0 ) {
3080       defineIn_RegMask(_CPP_MISC_file._fp, _globalNames, *oper);
3081 
3082       fprintf(fp,"MachOper  *%sOper::clone(Compile* C) const {\n", oper->_ident);
3083       fprintf(fp,"  return  new (C) %sOper(_label, _block_num);\n", oper->_ident);
3084       fprintf(fp,"}\n");
3085 
3086       fprintf(fp,"uint %sOper::opcode() const { return %s; }\n",
3087               oper->_ident, machOperEnum(oper->_ident));
3088       // // Currently all XXXOper::Hash() methods are identical (990820)
3089       // define_hash(fp, oper->_ident);
3090       // // Currently all XXXOper::Cmp() methods are identical (990820)
3091       // define_cmp(fp, oper->_ident);
3092       fprintf(fp,"\n");
3093 
3094       continue;
3095     }
3096 
3097     // The declaration of methodOper is in machine-independent file: machnode
3098     if ( strcmp(oper->_ident,"method") == 0 ) {
3099       defineIn_RegMask(_CPP_MISC_file._fp, _globalNames, *oper);
3100 
3101       fprintf(fp,"MachOper  *%sOper::clone(Compile* C) const {\n", oper->_ident);
3102       fprintf(fp,"  return  new (C) %sOper(_method);\n", oper->_ident);
3103       fprintf(fp,"}\n");
3104 
3105       fprintf(fp,"uint %sOper::opcode() const { return %s; }\n",
3106               oper->_ident, machOperEnum(oper->_ident));
3107       // // Currently all XXXOper::Hash() methods are identical (990820)
3108       // define_hash(fp, oper->_ident);
3109       // // Currently all XXXOper::Cmp() methods are identical (990820)
3110       // define_cmp(fp, oper->_ident);
3111       fprintf(fp,"\n");
3112 
3113       continue;
3114     }
3115 
3116     defineIn_RegMask(fp, _globalNames, *oper);
3117     defineClone(_CPP_CLONE_file._fp, _globalNames, *oper);
3118     // // Currently all XXXOper::Hash() methods are identical (990820)
3119     // define_hash(fp, oper->_ident);
3120     // // Currently all XXXOper::Cmp() methods are identical (990820)
3121     // define_cmp(fp, oper->_ident);
3122 
3123     // side-call to generate output that used to be in the header file:
3124     extern void gen_oper_format(FILE *fp, FormDict &globals, OperandForm &oper, bool for_c_file);
3125     gen_oper_format(_CPP_FORMAT_file._fp, _globalNames, *oper, true);
3126 
3127   }
3128 
3129 
3130   // Generate Machine Classes for each instruction defined in AD file
3131   fprintf(fp,"//------------------Define members for classes derived from MachNode----------\n");
3132   // Output the definitions for out_RegMask() // & kill_RegMask()
3133   _instructions.reset();
3134   InstructForm *instr;
3135   MachNodeForm *machnode;
3136   for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
3137     // Ensure this is a machine-world instruction
3138     if ( instr->ideal_only() ) continue;
3139 
3140     defineOut_RegMask(_CPP_MISC_file._fp, instr->_ident, reg_mask(*instr));
3141   }
3142 
3143   bool used = false;
3144   // Output the definitions for expand rules & peephole rules
3145   _instructions.reset();
3146   for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
3147     // Ensure this is a machine-world instruction
3148     if ( instr->ideal_only() ) continue;
3149     // If there are multiple defs/kills, or an explicit expand rule, build rule
3150     if( instr->expands() || instr->needs_projections() ||
3151         instr->has_temps() ||
3152         instr->is_mach_constant() ||
3153         instr->needs_constant_base() ||
3154         instr->_matrule != NULL &&
3155         instr->num_opnds() != instr->num_unique_opnds() )
3156       defineExpand(_CPP_EXPAND_file._fp, instr);
3157     // If there is an explicit peephole rule, build it
3158     if ( instr->peepholes() )
3159       definePeephole(_CPP_PEEPHOLE_file._fp, instr);
3160 
3161     // Output code to convert to the cisc version, if applicable
3162     used |= instr->define_cisc_version(*this, fp);
3163 
3164     // Output code to convert to the short branch version, if applicable
3165     used |= instr->define_short_branch_methods(*this, fp);
3166   }
3167 
3168   // Construct the method called by cisc_version() to copy inputs and operands.
3169   define_fill_new_machnode(used, fp);
3170 
3171   // Output the definitions for labels
3172   _instructions.reset();
3173   while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
3174     // Ensure this is a machine-world instruction
3175     if ( instr->ideal_only() ) continue;
3176 
3177     // Access the fields for operand Label
3178     int label_position = instr->label_position();
3179     if( label_position != -1 ) {
3180       // Set the label
3181       fprintf(fp,"void %sNode::label_set( Label* label, uint block_num ) {\n", instr->_ident);
3182       fprintf(fp,"  labelOper* oper  = (labelOper*)(opnd_array(%d));\n",
3183               label_position );
3184       fprintf(fp,"  oper->_label     = label;\n");
3185       fprintf(fp,"  oper->_block_num = block_num;\n");
3186       fprintf(fp,"}\n");
3187       // Save the label
3188       fprintf(fp,"void %sNode::save_label( Label** label, uint* block_num ) {\n", instr->_ident);
3189       fprintf(fp,"  labelOper* oper  = (labelOper*)(opnd_array(%d));\n",
3190               label_position );
3191       fprintf(fp,"  *label = oper->_label;\n");
3192       fprintf(fp,"  *block_num = oper->_block_num;\n");
3193       fprintf(fp,"}\n");
3194     }
3195   }
3196 
3197   // Output the definitions for methods
3198   _instructions.reset();
3199   while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
3200     // Ensure this is a machine-world instruction
3201     if ( instr->ideal_only() ) continue;
3202 
3203     // Access the fields for operand Label
3204     int method_position = instr->method_position();
3205     if( method_position != -1 ) {
3206       // Access the method's address
3207       fprintf(fp,"void %sNode::method_set( intptr_t method ) {\n", instr->_ident);
3208       fprintf(fp,"  ((methodOper*)opnd_array(%d))->_method = method;\n",
3209               method_position );
3210       fprintf(fp,"}\n");
3211       fprintf(fp,"\n");
3212     }
3213   }
3214 
3215   // Define this instruction's number of relocation entries, base is '0'
3216   _instructions.reset();
3217   while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
3218     // Output the definition for number of relocation entries
3219     uint reloc_size = instr->reloc(_globalNames);
3220     if ( reloc_size != 0 ) {
3221       fprintf(fp,"int %sNode::reloc() const {\n", instr->_ident);
3222       fprintf(fp,"  return %d;\n", reloc_size);
3223       fprintf(fp,"}\n");
3224       fprintf(fp,"\n");
3225     }
3226   }
3227   fprintf(fp,"\n");
3228 
3229   // Output the definitions for code generation
3230   //
3231   // address  ___Node::emit(address ptr, PhaseRegAlloc *ra_) const {
3232   //   // ...  encoding defined by user
3233   //   return ptr;
3234   // }
3235   //
3236   _instructions.reset();
3237   for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
3238     // Ensure this is a machine-world instruction
3239     if ( instr->ideal_only() ) continue;
3240 
3241     if (instr->_insencode) {
3242       if (instr->postalloc_expands()) {
3243         // Don't write this to _CPP_EXPAND_file, as the code generated calls C-code
3244         // from code sections in ad file that is dumped to fp.
3245         define_postalloc_expand(fp, *instr);
3246       } else {
3247         defineEmit(fp, *instr);
3248       }
3249     }
3250     if (instr->is_mach_constant()) defineEvalConstant(fp, *instr);
3251     if (instr->_size)              defineSize        (fp, *instr);
3252 
3253     // side-call to generate output that used to be in the header file:
3254     extern void gen_inst_format(FILE *fp, FormDict &globals, InstructForm &oper, bool for_c_file);
3255     gen_inst_format(_CPP_FORMAT_file._fp, _globalNames, *instr, true);
3256   }
3257 
3258   // Output the definitions for alias analysis
3259   _instructions.reset();
3260   for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
3261     // Ensure this is a machine-world instruction
3262     if ( instr->ideal_only() ) continue;
3263 
3264     // Analyze machine instructions that either USE or DEF memory.
3265     int memory_operand = instr->memory_operand(_globalNames);
3266     // Some guys kill all of memory
3267     if ( instr->is_wide_memory_kill(_globalNames) ) {
3268       memory_operand = InstructForm::MANY_MEMORY_OPERANDS;
3269     }
3270 
3271     if ( memory_operand != InstructForm::NO_MEMORY_OPERAND ) {
3272       if( memory_operand == InstructForm::MANY_MEMORY_OPERANDS ) {
3273         fprintf(fp,"const TypePtr *%sNode::adr_type() const { return TypePtr::BOTTOM; }\n", instr->_ident);
3274         fprintf(fp,"const MachOper* %sNode::memory_operand() const { return (MachOper*)-1; }\n", instr->_ident);
3275       } else {
3276         fprintf(fp,"const MachOper* %sNode::memory_operand() const { return _opnds[%d]; }\n", instr->_ident, memory_operand);
3277   }
3278     }
3279   }
3280 
3281   // Get the length of the longest identifier
3282   int max_ident_len = 0;
3283   _instructions.reset();
3284 
3285   for ( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
3286     if (instr->_ins_pipe && _pipeline->_classlist.search(instr->_ins_pipe)) {
3287       int ident_len = (int)strlen(instr->_ident);
3288       if( max_ident_len < ident_len )
3289         max_ident_len = ident_len;
3290     }
3291   }
3292 
3293   // Emit specifically for Node(s)
3294   fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*s::pipeline_class() { return %s; }\n",
3295     max_ident_len, "Node", _pipeline ? "(&pipeline_class_Zero_Instructions)" : "NULL");
3296   fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*s::pipeline() const { return %s; }\n",
3297     max_ident_len, "Node", _pipeline ? "(&pipeline_class_Zero_Instructions)" : "NULL");
3298   fprintf(_CPP_PIPELINE_file._fp, "\n");
3299 
3300   fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*s::pipeline_class() { return %s; }\n",
3301     max_ident_len, "MachNode", _pipeline ? "(&pipeline_class_Unknown_Instructions)" : "NULL");
3302   fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*s::pipeline() const { return pipeline_class(); }\n",
3303     max_ident_len, "MachNode");
3304   fprintf(_CPP_PIPELINE_file._fp, "\n");
3305 
3306   // Output the definitions for machine node specific pipeline data
3307   _machnodes.reset();
3308 
3309   for ( ; (machnode = (MachNodeForm*)_machnodes.iter()) != NULL; ) {
3310     fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %sNode::pipeline() const { return (&pipeline_class_%03d); }\n",
3311       machnode->_ident, ((class PipeClassForm *)_pipeline->_classdict[machnode->_machnode_pipe])->_num);
3312   }
3313 
3314   fprintf(_CPP_PIPELINE_file._fp, "\n");
3315 
3316   // Output the definitions for instruction pipeline static data references
3317   _instructions.reset();
3318 
3319   for ( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
3320     if (instr->_ins_pipe && _pipeline->_classlist.search(instr->_ins_pipe)) {
3321       fprintf(_CPP_PIPELINE_file._fp, "\n");
3322       fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*sNode::pipeline_class() { return (&pipeline_class_%03d); }\n",
3323         max_ident_len, instr->_ident, ((class PipeClassForm *)_pipeline->_classdict[instr->_ins_pipe])->_num);
3324       fprintf(_CPP_PIPELINE_file._fp, "const Pipeline * %*sNode::pipeline() const { return (&pipeline_class_%03d); }\n",
3325         max_ident_len, instr->_ident, ((class PipeClassForm *)_pipeline->_classdict[instr->_ins_pipe])->_num);
3326     }
3327   }
3328 }
3329 
3330 
3331 // -------------------------------- maps ------------------------------------
3332 
3333 // Information needed to generate the ReduceOp mapping for the DFA
3334 class OutputReduceOp : public OutputMap {
3335 public:
3336   OutputReduceOp(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD)
3337     : OutputMap(hpp, cpp, globals, AD, "reduceOp") {};
3338 
3339   void declaration() { fprintf(_hpp, "extern const int   reduceOp[];\n"); }
3340   void definition()  { fprintf(_cpp, "const        int   reduceOp[] = {\n"); }
3341   void closing()     { fprintf(_cpp, "  0 // no trailing comma\n");
3342                        OutputMap::closing();
3343   }
3344   void map(OpClassForm &opc)  {
3345     const char *reduce = opc._ident;
3346     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3347     else          fprintf(_cpp, "  0");
3348   }
3349   void map(OperandForm &oper) {
3350     // Most operands without match rules, e.g.  eFlagsReg, do not have a result operand
3351     const char *reduce = (oper._matrule ? oper.reduce_result() : NULL);
3352     // operand stackSlot does not have a match rule, but produces a stackSlot
3353     if( oper.is_user_name_for_sReg() != Form::none ) reduce = oper.reduce_result();
3354     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3355     else          fprintf(_cpp, "  0");
3356   }
3357   void map(InstructForm &inst) {
3358     const char *reduce = (inst._matrule ? inst.reduce_result() : NULL);
3359     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3360     else          fprintf(_cpp, "  0");
3361   }
3362   void map(char         *reduce) {
3363     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3364     else          fprintf(_cpp, "  0");
3365   }
3366 };
3367 
3368 // Information needed to generate the LeftOp mapping for the DFA
3369 class OutputLeftOp : public OutputMap {
3370 public:
3371   OutputLeftOp(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD)
3372     : OutputMap(hpp, cpp, globals, AD, "leftOp") {};
3373 
3374   void declaration() { fprintf(_hpp, "extern const int   leftOp[];\n"); }
3375   void definition()  { fprintf(_cpp, "const        int   leftOp[] = {\n"); }
3376   void closing()     { fprintf(_cpp, "  0 // no trailing comma\n");
3377                        OutputMap::closing();
3378   }
3379   void map(OpClassForm &opc)  { fprintf(_cpp, "  0"); }
3380   void map(OperandForm &oper) {
3381     const char *reduce = oper.reduce_left(_globals);
3382     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3383     else          fprintf(_cpp, "  0");
3384   }
3385   void map(char        *name) {
3386     const char *reduce = _AD.reduceLeft(name);
3387     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3388     else          fprintf(_cpp, "  0");
3389   }
3390   void map(InstructForm &inst) {
3391     const char *reduce = inst.reduce_left(_globals);
3392     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3393     else          fprintf(_cpp, "  0");
3394   }
3395 };
3396 
3397 
3398 // Information needed to generate the RightOp mapping for the DFA
3399 class OutputRightOp : public OutputMap {
3400 public:
3401   OutputRightOp(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD)
3402     : OutputMap(hpp, cpp, globals, AD, "rightOp") {};
3403 
3404   void declaration() { fprintf(_hpp, "extern const int   rightOp[];\n"); }
3405   void definition()  { fprintf(_cpp, "const        int   rightOp[] = {\n"); }
3406   void closing()     { fprintf(_cpp, "  0 // no trailing comma\n");
3407                        OutputMap::closing();
3408   }
3409   void map(OpClassForm &opc)  { fprintf(_cpp, "  0"); }
3410   void map(OperandForm &oper) {
3411     const char *reduce = oper.reduce_right(_globals);
3412     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3413     else          fprintf(_cpp, "  0");
3414   }
3415   void map(char        *name) {
3416     const char *reduce = _AD.reduceRight(name);
3417     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3418     else          fprintf(_cpp, "  0");
3419   }
3420   void map(InstructForm &inst) {
3421     const char *reduce = inst.reduce_right(_globals);
3422     if( reduce )  fprintf(_cpp, "  %s_rule", reduce);
3423     else          fprintf(_cpp, "  0");
3424   }
3425 };
3426 
3427 
3428 // Information needed to generate the Rule names for the DFA
3429 class OutputRuleName : public OutputMap {
3430 public:
3431   OutputRuleName(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD)
3432     : OutputMap(hpp, cpp, globals, AD, "ruleName") {};
3433 
3434   void declaration() { fprintf(_hpp, "extern const char *ruleName[];\n"); }
3435   void definition()  { fprintf(_cpp, "const char        *ruleName[] = {\n"); }
3436   void closing()     { fprintf(_cpp, "  \"invalid rule name\" // no trailing comma\n");
3437                        OutputMap::closing();
3438   }
3439   void map(OpClassForm &opc)  { fprintf(_cpp, "  \"%s\"", _AD.machOperEnum(opc._ident) ); }
3440   void map(OperandForm &oper) { fprintf(_cpp, "  \"%s\"", _AD.machOperEnum(oper._ident) ); }
3441   void map(char        *name) { fprintf(_cpp, "  \"%s\"", name ? name : "0"); }
3442   void map(InstructForm &inst){ fprintf(_cpp, "  \"%s\"", inst._ident ? inst._ident : "0"); }
3443 };
3444 
3445 
3446 // Information needed to generate the swallowed mapping for the DFA
3447 class OutputSwallowed : public OutputMap {
3448 public:
3449   OutputSwallowed(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD)
3450     : OutputMap(hpp, cpp, globals, AD, "swallowed") {};
3451 
3452   void declaration() { fprintf(_hpp, "extern const bool  swallowed[];\n"); }
3453   void definition()  { fprintf(_cpp, "const        bool  swallowed[] = {\n"); }
3454   void closing()     { fprintf(_cpp, "  false // no trailing comma\n");
3455                        OutputMap::closing();
3456   }
3457   void map(OperandForm &oper) { // Generate the entry for this opcode
3458     const char *swallowed = oper.swallowed(_globals) ? "true" : "false";
3459     fprintf(_cpp, "  %s", swallowed);
3460   }
3461   void map(OpClassForm &opc)  { fprintf(_cpp, "  false"); }
3462   void map(char        *name) { fprintf(_cpp, "  false"); }
3463   void map(InstructForm &inst){ fprintf(_cpp, "  false"); }
3464 };
3465 
3466 
3467 // Information needed to generate the decision array for instruction chain rule
3468 class OutputInstChainRule : public OutputMap {
3469 public:
3470   OutputInstChainRule(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD)
3471     : OutputMap(hpp, cpp, globals, AD, "instruction_chain_rule") {};
3472 
3473   void declaration() { fprintf(_hpp, "extern const bool  instruction_chain_rule[];\n"); }
3474   void definition()  { fprintf(_cpp, "const        bool  instruction_chain_rule[] = {\n"); }
3475   void closing()     { fprintf(_cpp, "  false // no trailing comma\n");
3476                        OutputMap::closing();
3477   }
3478   void map(OpClassForm &opc)   { fprintf(_cpp, "  false"); }
3479   void map(OperandForm &oper)  { fprintf(_cpp, "  false"); }
3480   void map(char        *name)  { fprintf(_cpp, "  false"); }
3481   void map(InstructForm &inst) { // Check for simple chain rule
3482     const char *chain = inst.is_simple_chain_rule(_globals) ? "true" : "false";
3483     fprintf(_cpp, "  %s", chain);
3484   }
3485 };
3486 
3487 
3488 //---------------------------build_map------------------------------------
3489 // Build  mapping from enumeration for densely packed operands
3490 // TO result and child types.
3491 void ArchDesc::build_map(OutputMap &map) {
3492   FILE         *fp_hpp = map.decl_file();
3493   FILE         *fp_cpp = map.def_file();
3494   int           idx    = 0;
3495   OperandForm  *op;
3496   OpClassForm  *opc;
3497   InstructForm *inst;
3498 
3499   // Construct this mapping
3500   map.declaration();
3501   fprintf(fp_cpp,"\n");
3502   map.definition();
3503 
3504   // Output the mapping for operands
3505   map.record_position(OutputMap::BEGIN_OPERANDS, idx );
3506   _operands.reset();
3507   for(; (op = (OperandForm*)_operands.iter()) != NULL; ) {
3508     // Ensure this is a machine-world instruction
3509     if ( op->ideal_only() )  continue;
3510 
3511     // Generate the entry for this opcode
3512     fprintf(fp_cpp, "  /* %4d */", idx); map.map(*op); fprintf(fp_cpp, ",\n");
3513     ++idx;
3514   };
3515   fprintf(fp_cpp, "  // last operand\n");
3516 
3517   // Place all user-defined operand classes into the mapping
3518   map.record_position(OutputMap::BEGIN_OPCLASSES, idx );
3519   _opclass.reset();
3520   for(; (opc = (OpClassForm*)_opclass.iter()) != NULL; ) {
3521     fprintf(fp_cpp, "  /* %4d */", idx); map.map(*opc); fprintf(fp_cpp, ",\n");
3522     ++idx;
3523   };
3524   fprintf(fp_cpp, "  // last operand class\n");
3525 
3526   // Place all internally defined operands into the mapping
3527   map.record_position(OutputMap::BEGIN_INTERNALS, idx );
3528   _internalOpNames.reset();
3529   char *name = NULL;
3530   for(; (name = (char *)_internalOpNames.iter()) != NULL; ) {
3531     fprintf(fp_cpp, "  /* %4d */", idx); map.map(name); fprintf(fp_cpp, ",\n");
3532     ++idx;
3533   };
3534   fprintf(fp_cpp, "  // last internally defined operand\n");
3535 
3536   // Place all user-defined instructions into the mapping
3537   if( map.do_instructions() ) {
3538     map.record_position(OutputMap::BEGIN_INSTRUCTIONS, idx );
3539     // Output all simple instruction chain rules first
3540     map.record_position(OutputMap::BEGIN_INST_CHAIN_RULES, idx );
3541     {
3542       _instructions.reset();
3543       for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
3544         // Ensure this is a machine-world instruction
3545         if ( inst->ideal_only() )  continue;
3546         if ( ! inst->is_simple_chain_rule(_globalNames) ) continue;
3547         if ( inst->rematerialize(_globalNames, get_registers()) ) continue;
3548 
3549         fprintf(fp_cpp, "  /* %4d */", idx); map.map(*inst); fprintf(fp_cpp, ",\n");
3550         ++idx;
3551       };
3552       map.record_position(OutputMap::BEGIN_REMATERIALIZE, idx );
3553       _instructions.reset();
3554       for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
3555         // Ensure this is a machine-world instruction
3556         if ( inst->ideal_only() )  continue;
3557         if ( ! inst->is_simple_chain_rule(_globalNames) ) continue;
3558         if ( ! inst->rematerialize(_globalNames, get_registers()) ) continue;
3559 
3560         fprintf(fp_cpp, "  /* %4d */", idx); map.map(*inst); fprintf(fp_cpp, ",\n");
3561         ++idx;
3562       };
3563       map.record_position(OutputMap::END_INST_CHAIN_RULES, idx );
3564     }
3565     // Output all instructions that are NOT simple chain rules
3566     {
3567       _instructions.reset();
3568       for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
3569         // Ensure this is a machine-world instruction
3570         if ( inst->ideal_only() )  continue;
3571         if ( inst->is_simple_chain_rule(_globalNames) ) continue;
3572         if ( ! inst->rematerialize(_globalNames, get_registers()) ) continue;
3573 
3574         fprintf(fp_cpp, "  /* %4d */", idx); map.map(*inst); fprintf(fp_cpp, ",\n");
3575         ++idx;
3576       };
3577       map.record_position(OutputMap::END_REMATERIALIZE, idx );
3578       _instructions.reset();
3579       for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
3580         // Ensure this is a machine-world instruction
3581         if ( inst->ideal_only() )  continue;
3582         if ( inst->is_simple_chain_rule(_globalNames) ) continue;
3583         if ( inst->rematerialize(_globalNames, get_registers()) ) continue;
3584 
3585         fprintf(fp_cpp, "  /* %4d */", idx); map.map(*inst); fprintf(fp_cpp, ",\n");
3586         ++idx;
3587       };
3588     }
3589     fprintf(fp_cpp, "  // last instruction\n");
3590     map.record_position(OutputMap::END_INSTRUCTIONS, idx );
3591   }
3592   // Finish defining table
3593   map.closing();
3594 };
3595 
3596 
3597 // Helper function for buildReduceMaps
3598 char reg_save_policy(const char *calling_convention) {
3599   char callconv;
3600 
3601   if      (!strcmp(calling_convention, "NS"))  callconv = 'N';
3602   else if (!strcmp(calling_convention, "SOE")) callconv = 'E';
3603   else if (!strcmp(calling_convention, "SOC")) callconv = 'C';
3604   else if (!strcmp(calling_convention, "AS"))  callconv = 'A';
3605   else                                         callconv = 'Z';
3606 
3607   return callconv;
3608 }
3609 
3610 void ArchDesc::generate_needs_clone_jvms(FILE *fp_cpp) {
3611   fprintf(fp_cpp, "bool Compile::needs_clone_jvms() { return %s; }\n\n",
3612           _needs_clone_jvms ? "true" : "false");
3613 }
3614 
3615 //---------------------------generate_assertion_checks-------------------
3616 void ArchDesc::generate_adlc_verification(FILE *fp_cpp) {
3617   fprintf(fp_cpp, "\n");
3618 
3619   fprintf(fp_cpp, "#ifndef PRODUCT\n");
3620   fprintf(fp_cpp, "void Compile::adlc_verification() {\n");
3621   globalDefs().print_asserts(fp_cpp);
3622   fprintf(fp_cpp, "}\n");
3623   fprintf(fp_cpp, "#endif\n");
3624   fprintf(fp_cpp, "\n");
3625 }
3626 
3627 //---------------------------addSourceBlocks-----------------------------
3628 void ArchDesc::addSourceBlocks(FILE *fp_cpp) {
3629   if (_source.count() > 0)
3630     _source.output(fp_cpp);
3631 
3632   generate_adlc_verification(fp_cpp);
3633 }
3634 //---------------------------addHeaderBlocks-----------------------------
3635 void ArchDesc::addHeaderBlocks(FILE *fp_hpp) {
3636   if (_header.count() > 0)
3637     _header.output(fp_hpp);
3638 }
3639 //-------------------------addPreHeaderBlocks----------------------------
3640 void ArchDesc::addPreHeaderBlocks(FILE *fp_hpp) {
3641   // Output #defines from definition block
3642   globalDefs().print_defines(fp_hpp);
3643 
3644   if (_pre_header.count() > 0)
3645     _pre_header.output(fp_hpp);
3646 }
3647 
3648 //---------------------------buildReduceMaps-----------------------------
3649 // Build  mapping from enumeration for densely packed operands
3650 // TO result and child types.
3651 void ArchDesc::buildReduceMaps(FILE *fp_hpp, FILE *fp_cpp) {
3652   RegDef       *rdef;
3653   RegDef       *next;
3654 
3655   // The emit bodies currently require functions defined in the source block.
3656 
3657   // Build external declarations for mappings
3658   fprintf(fp_hpp, "\n");
3659   fprintf(fp_hpp, "extern const char  register_save_policy[];\n");
3660   fprintf(fp_hpp, "extern const char  c_reg_save_policy[];\n");
3661   fprintf(fp_hpp, "extern const int   register_save_type[];\n");
3662   fprintf(fp_hpp, "\n");
3663 
3664   // Construct Save-Policy array
3665   fprintf(fp_cpp, "// Map from machine-independent register number to register_save_policy\n");
3666   fprintf(fp_cpp, "const        char register_save_policy[] = {\n");
3667   _register->reset_RegDefs();
3668   for( rdef = _register->iter_RegDefs(); rdef != NULL; rdef = next ) {
3669     next              = _register->iter_RegDefs();
3670     char policy       = reg_save_policy(rdef->_callconv);
3671     const char *comma = (next != NULL) ? "," : " // no trailing comma";
3672     fprintf(fp_cpp, "  '%c'%s // %s\n", policy, comma, rdef->_regname);
3673   }
3674   fprintf(fp_cpp, "};\n\n");
3675 
3676   // Construct Native Save-Policy array
3677   fprintf(fp_cpp, "// Map from machine-independent register number to c_reg_save_policy\n");
3678   fprintf(fp_cpp, "const        char c_reg_save_policy[] = {\n");
3679   _register->reset_RegDefs();
3680   for( rdef = _register->iter_RegDefs(); rdef != NULL; rdef = next ) {
3681     next        = _register->iter_RegDefs();
3682     char policy = reg_save_policy(rdef->_c_conv);
3683     const char *comma = (next != NULL) ? "," : " // no trailing comma";
3684     fprintf(fp_cpp, "  '%c'%s // %s\n", policy, comma, rdef->_regname);
3685   }
3686   fprintf(fp_cpp, "};\n\n");
3687 
3688   // Construct Register Save Type array
3689   fprintf(fp_cpp, "// Map from machine-independent register number to register_save_type\n");
3690   fprintf(fp_cpp, "const        int register_save_type[] = {\n");
3691   _register->reset_RegDefs();
3692   for( rdef = _register->iter_RegDefs(); rdef != NULL; rdef = next ) {
3693     next = _register->iter_RegDefs();
3694     const char *comma = (next != NULL) ? "," : " // no trailing comma";
3695     fprintf(fp_cpp, "  %s%s\n", rdef->_idealtype, comma);
3696   }
3697   fprintf(fp_cpp, "};\n\n");
3698 
3699   // Construct the table for reduceOp
3700   OutputReduceOp output_reduce_op(fp_hpp, fp_cpp, _globalNames, *this);
3701   build_map(output_reduce_op);
3702   // Construct the table for leftOp
3703   OutputLeftOp output_left_op(fp_hpp, fp_cpp, _globalNames, *this);
3704   build_map(output_left_op);
3705   // Construct the table for rightOp
3706   OutputRightOp output_right_op(fp_hpp, fp_cpp, _globalNames, *this);
3707   build_map(output_right_op);
3708   // Construct the table of rule names
3709   OutputRuleName output_rule_name(fp_hpp, fp_cpp, _globalNames, *this);
3710   build_map(output_rule_name);
3711   // Construct the boolean table for subsumed operands
3712   OutputSwallowed output_swallowed(fp_hpp, fp_cpp, _globalNames, *this);
3713   build_map(output_swallowed);
3714   // // // Preserve in case we decide to use this table instead of another
3715   //// Construct the boolean table for instruction chain rules
3716   //OutputInstChainRule output_inst_chain(fp_hpp, fp_cpp, _globalNames, *this);
3717   //build_map(output_inst_chain);
3718 
3719 }
3720 
3721 
3722 //---------------------------buildMachOperGenerator---------------------------
3723 
3724 // Recurse through match tree, building path through corresponding state tree,
3725 // Until we reach the constant we are looking for.
3726 static void path_to_constant(FILE *fp, FormDict &globals,
3727                              MatchNode *mnode, uint idx) {
3728   if ( ! mnode) return;
3729 
3730   unsigned    position = 0;
3731   const char *result   = NULL;
3732   const char *name     = NULL;
3733   const char *optype   = NULL;
3734 
3735   // Base Case: access constant in ideal node linked to current state node
3736   // Each type of constant has its own access function
3737   if ( (mnode->_lChild == NULL) && (mnode->_rChild == NULL)
3738        && mnode->base_operand(position, globals, result, name, optype) ) {
3739     if (         strcmp(optype,"ConI") == 0 ) {
3740       fprintf(fp, "_leaf->get_int()");
3741     } else if ( (strcmp(optype,"ConP") == 0) ) {
3742       fprintf(fp, "_leaf->bottom_type()->is_ptr()");
3743     } else if ( (strcmp(optype,"ConN") == 0) ) {
3744       fprintf(fp, "_leaf->bottom_type()->is_narrowoop()");
3745     } else if ( (strcmp(optype,"ConNKlass") == 0) ) {
3746       fprintf(fp, "_leaf->bottom_type()->is_narrowklass()");
3747     } else if ( (strcmp(optype,"ConF") == 0) ) {
3748       fprintf(fp, "_leaf->getf()");
3749     } else if ( (strcmp(optype,"ConD") == 0) ) {
3750       fprintf(fp, "_leaf->getd()");
3751     } else if ( (strcmp(optype,"ConL") == 0) ) {
3752       fprintf(fp, "_leaf->get_long()");
3753     } else if ( (strcmp(optype,"Con")==0) ) {
3754       // !!!!! - Update if adding a machine-independent constant type
3755       fprintf(fp, "_leaf->get_int()");
3756       assert( false, "Unsupported constant type, pointer or indefinite");
3757     } else if ( (strcmp(optype,"Bool") == 0) ) {
3758       fprintf(fp, "_leaf->as_Bool()->_test._test");
3759     } else {
3760       assert( false, "Unsupported constant type");
3761     }
3762     return;
3763   }
3764 
3765   // If constant is in left child, build path and recurse
3766   uint lConsts = (mnode->_lChild) ? (mnode->_lChild->num_consts(globals) ) : 0;
3767   uint rConsts = (mnode->_rChild) ? (mnode->_rChild->num_consts(globals) ) : 0;
3768   if ( (mnode->_lChild) && (lConsts > idx) ) {
3769     fprintf(fp, "_kids[0]->");
3770     path_to_constant(fp, globals, mnode->_lChild, idx);
3771     return;
3772   }
3773   // If constant is in right child, build path and recurse
3774   if ( (mnode->_rChild) && (rConsts > (idx - lConsts) ) ) {
3775     idx = idx - lConsts;
3776     fprintf(fp, "_kids[1]->");
3777     path_to_constant(fp, globals, mnode->_rChild, idx);
3778     return;
3779   }
3780   assert( false, "ShouldNotReachHere()");
3781 }
3782 
3783 // Generate code that is executed when generating a specific Machine Operand
3784 static void genMachOperCase(FILE *fp, FormDict &globalNames, ArchDesc &AD,
3785                             OperandForm &op) {
3786   const char *opName         = op._ident;
3787   const char *opEnumName     = AD.machOperEnum(opName);
3788   uint        num_consts     = op.num_consts(globalNames);
3789 
3790   // Generate the case statement for this opcode
3791   fprintf(fp, "  case %s:", opEnumName);
3792   fprintf(fp, "\n    return new (C) %sOper(", opName);
3793   // Access parameters for constructor from the stat object
3794   //
3795   // Build access to condition code value
3796   if ( (num_consts > 0) ) {
3797     uint i = 0;
3798     path_to_constant(fp, globalNames, op._matrule, i);
3799     for ( i = 1; i < num_consts; ++i ) {
3800       fprintf(fp, ", ");
3801       path_to_constant(fp, globalNames, op._matrule, i);
3802     }
3803   }
3804   fprintf(fp, " );\n");
3805 }
3806 
3807 
3808 // Build switch to invoke "new" MachNode or MachOper
3809 void ArchDesc::buildMachOperGenerator(FILE *fp_cpp) {
3810   int idx = 0;
3811 
3812   // Build switch to invoke 'new' for a specific MachOper
3813   fprintf(fp_cpp, "\n");
3814   fprintf(fp_cpp, "\n");
3815   fprintf(fp_cpp,
3816           "//------------------------- MachOper Generator ---------------\n");
3817   fprintf(fp_cpp,
3818           "// A switch statement on the dense-packed user-defined type system\n"
3819           "// that invokes 'new' on the corresponding class constructor.\n");
3820   fprintf(fp_cpp, "\n");
3821   fprintf(fp_cpp, "MachOper *State::MachOperGenerator");
3822   fprintf(fp_cpp, "(int opcode, Compile* C)");
3823   fprintf(fp_cpp, "{\n");
3824   fprintf(fp_cpp, "\n");
3825   fprintf(fp_cpp, "  switch(opcode) {\n");
3826 
3827   // Place all user-defined operands into the mapping
3828   _operands.reset();
3829   int  opIndex = 0;
3830   OperandForm *op;
3831   for( ; (op =  (OperandForm*)_operands.iter()) != NULL; ) {
3832     // Ensure this is a machine-world instruction
3833     if ( op->ideal_only() )  continue;
3834 
3835     genMachOperCase(fp_cpp, _globalNames, *this, *op);
3836   };
3837 
3838   // Do not iterate over operand classes for the  operand generator!!!
3839 
3840   // Place all internal operands into the mapping
3841   _internalOpNames.reset();
3842   const char *iopn;
3843   for( ; (iopn =  _internalOpNames.iter()) != NULL; ) {
3844     const char *opEnumName = machOperEnum(iopn);
3845     // Generate the case statement for this opcode
3846     fprintf(fp_cpp, "  case %s:", opEnumName);
3847     fprintf(fp_cpp, "    return NULL;\n");
3848   };
3849 
3850   // Generate the default case for switch(opcode)
3851   fprintf(fp_cpp, "  \n");
3852   fprintf(fp_cpp, "  default:\n");
3853   fprintf(fp_cpp, "    fprintf(stderr, \"Default MachOper Generator invoked for: \\n\");\n");
3854   fprintf(fp_cpp, "    fprintf(stderr, \"   opcode = %cd\\n\", opcode);\n", '%');
3855   fprintf(fp_cpp, "    break;\n");
3856   fprintf(fp_cpp, "  }\n");
3857 
3858   // Generate the closing for method Matcher::MachOperGenerator
3859   fprintf(fp_cpp, "  return NULL;\n");
3860   fprintf(fp_cpp, "};\n");
3861 }
3862 
3863 
3864 //---------------------------buildMachNode-------------------------------------
3865 // Build a new MachNode, for MachNodeGenerator or cisc-spilling
3866 void ArchDesc::buildMachNode(FILE *fp_cpp, InstructForm *inst, const char *indent) {
3867   const char *opType  = NULL;
3868   const char *opClass = inst->_ident;
3869 
3870   // Create the MachNode object
3871   fprintf(fp_cpp, "%s %sNode *node = new (C) %sNode();\n",indent, opClass,opClass);
3872 
3873   if ( (inst->num_post_match_opnds() != 0) ) {
3874     // Instruction that contains operands which are not in match rule.
3875     //
3876     // Check if the first post-match component may be an interesting def
3877     bool           dont_care = false;
3878     ComponentList &comp_list = inst->_components;
3879     Component     *comp      = NULL;
3880     comp_list.reset();
3881     if ( comp_list.match_iter() != NULL )    dont_care = true;
3882 
3883     // Insert operands that are not in match-rule.
3884     // Only insert a DEF if the do_care flag is set
3885     comp_list.reset();
3886     while ( comp = comp_list.post_match_iter() ) {
3887       // Check if we don't care about DEFs or KILLs that are not USEs
3888       if ( dont_care && (! comp->isa(Component::USE)) ) {
3889         continue;
3890       }
3891       dont_care = true;
3892       // For each operand not in the match rule, call MachOperGenerator
3893       // with the enum for the opcode that needs to be built.
3894       ComponentList clist = inst->_components;
3895       int         index  = clist.operand_position(comp->_name, comp->_usedef, inst);
3896       const char *opcode = machOperEnum(comp->_type);
3897       fprintf(fp_cpp, "%s node->set_opnd_array(%d, ", indent, index);
3898       fprintf(fp_cpp, "MachOperGenerator(%s, C));\n", opcode);
3899       }
3900   }
3901   else if ( inst->is_chain_of_constant(_globalNames, opType) ) {
3902     // An instruction that chains from a constant!
3903     // In this case, we need to subsume the constant into the node
3904     // at operand position, oper_input_base().
3905     //
3906     // Fill in the constant
3907     fprintf(fp_cpp, "%s node->_opnd_array[%d] = ", indent,
3908             inst->oper_input_base(_globalNames));
3909     // #####
3910     // Check for multiple constants and then fill them in.
3911     // Just like MachOperGenerator
3912     const char *opName = inst->_matrule->_rChild->_opType;
3913     fprintf(fp_cpp, "new (C) %sOper(", opName);
3914     // Grab operand form
3915     OperandForm *op = (_globalNames[opName])->is_operand();
3916     // Look up the number of constants
3917     uint num_consts = op->num_consts(_globalNames);
3918     if ( (num_consts > 0) ) {
3919       uint i = 0;
3920       path_to_constant(fp_cpp, _globalNames, op->_matrule, i);
3921       for ( i = 1; i < num_consts; ++i ) {
3922         fprintf(fp_cpp, ", ");
3923         path_to_constant(fp_cpp, _globalNames, op->_matrule, i);
3924       }
3925     }
3926     fprintf(fp_cpp, " );\n");
3927     // #####
3928   }
3929 
3930   // Fill in the bottom_type where requested
3931   if (inst->captures_bottom_type(_globalNames)) {
3932     if (strncmp("MachCall", inst->mach_base_class(_globalNames), strlen("MachCall"))) {
3933       fprintf(fp_cpp, "%s node->_bottom_type = _leaf->bottom_type();\n", indent);
3934     }
3935   }
3936   if( inst->is_ideal_if() ) {
3937     fprintf(fp_cpp, "%s node->_prob = _leaf->as_If()->_prob;\n", indent);
3938     fprintf(fp_cpp, "%s node->_fcnt = _leaf->as_If()->_fcnt;\n", indent);
3939   }
3940   if( inst->is_ideal_fastlock() ) {
3941     fprintf(fp_cpp, "%s node->_counters = _leaf->as_FastLock()->counters();\n", indent);
3942     fprintf(fp_cpp, "%s node->_rtm_counters = _leaf->as_FastLock()->rtm_counters();\n", indent);
3943     fprintf(fp_cpp, "%s node->_stack_rtm_counters = _leaf->as_FastLock()->stack_rtm_counters();\n", indent);
3944   }
3945 
3946 }
3947 
3948 //---------------------------declare_cisc_version------------------------------
3949 // Build CISC version of this instruction
3950 void InstructForm::declare_cisc_version(ArchDesc &AD, FILE *fp_hpp) {
3951   if( AD.can_cisc_spill() ) {
3952     InstructForm *inst_cisc = cisc_spill_alternate();
3953     if (inst_cisc != NULL) {
3954       fprintf(fp_hpp, "  virtual int            cisc_operand() const { return %d; }\n", cisc_spill_operand());
3955       fprintf(fp_hpp, "  virtual MachNode      *cisc_version(int offset, Compile* C);\n");
3956       fprintf(fp_hpp, "  virtual void           use_cisc_RegMask();\n");
3957       fprintf(fp_hpp, "  virtual const RegMask *cisc_RegMask() const { return _cisc_RegMask; }\n");
3958     }
3959   }
3960 }
3961 
3962 //---------------------------define_cisc_version-------------------------------
3963 // Build CISC version of this instruction
3964 bool InstructForm::define_cisc_version(ArchDesc &AD, FILE *fp_cpp) {
3965   InstructForm *inst_cisc = this->cisc_spill_alternate();
3966   if( AD.can_cisc_spill() && (inst_cisc != NULL) ) {
3967     const char   *name      = inst_cisc->_ident;
3968     assert( inst_cisc->num_opnds() == this->num_opnds(), "Must have same number of operands");
3969     OperandForm *cisc_oper = AD.cisc_spill_operand();
3970     assert( cisc_oper != NULL, "insanity check");
3971     const char *cisc_oper_name  = cisc_oper->_ident;
3972     assert( cisc_oper_name != NULL, "insanity check");
3973     //
3974     // Set the correct reg_mask_or_stack for the cisc operand
3975     fprintf(fp_cpp, "\n");
3976     fprintf(fp_cpp, "void %sNode::use_cisc_RegMask() {\n", this->_ident);
3977     // Lookup the correct reg_mask_or_stack
3978     const char *reg_mask_name = cisc_reg_mask_name();
3979     fprintf(fp_cpp, "  _cisc_RegMask = &STACK_OR_%s;\n", reg_mask_name);
3980     fprintf(fp_cpp, "}\n");
3981     //
3982     // Construct CISC version of this instruction
3983     fprintf(fp_cpp, "\n");
3984     fprintf(fp_cpp, "// Build CISC version of this instruction\n");
3985     fprintf(fp_cpp, "MachNode *%sNode::cisc_version( int offset, Compile* C ) {\n", this->_ident);
3986     // Create the MachNode object
3987     fprintf(fp_cpp, "  %sNode *node = new (C) %sNode();\n", name, name);
3988     // Fill in the bottom_type where requested
3989     if ( this->captures_bottom_type(AD.globalNames()) ) {
3990       fprintf(fp_cpp, "  node->_bottom_type = bottom_type();\n");
3991     }
3992 
3993     uint cur_num_opnds = num_opnds();
3994     if (cur_num_opnds > 1 && cur_num_opnds != num_unique_opnds()) {
3995       fprintf(fp_cpp,"  node->_num_opnds = %d;\n", num_unique_opnds());
3996     }
3997 
3998     fprintf(fp_cpp, "\n");
3999     fprintf(fp_cpp, "  // Copy _idx, inputs and operands to new node\n");
4000     fprintf(fp_cpp, "  fill_new_machnode(node, C);\n");
4001     // Construct operand to access [stack_pointer + offset]
4002     fprintf(fp_cpp, "  // Construct operand to access [stack_pointer + offset]\n");
4003     fprintf(fp_cpp, "  node->set_opnd_array(cisc_operand(), new (C) %sOper(offset));\n", cisc_oper_name);
4004     fprintf(fp_cpp, "\n");
4005 
4006     // Return result and exit scope
4007     fprintf(fp_cpp, "  return node;\n");
4008     fprintf(fp_cpp, "}\n");
4009     fprintf(fp_cpp, "\n");
4010     return true;
4011   }
4012   return false;
4013 }
4014 
4015 //---------------------------declare_short_branch_methods----------------------
4016 // Build prototypes for short branch methods
4017 void InstructForm::declare_short_branch_methods(FILE *fp_hpp) {
4018   if (has_short_branch_form()) {
4019     fprintf(fp_hpp, "  virtual MachNode      *short_branch_version(Compile* C);\n");
4020   }
4021 }
4022 
4023 //---------------------------define_short_branch_methods-----------------------
4024 // Build definitions for short branch methods
4025 bool InstructForm::define_short_branch_methods(ArchDesc &AD, FILE *fp_cpp) {
4026   if (has_short_branch_form()) {
4027     InstructForm *short_branch = short_branch_form();
4028     const char   *name         = short_branch->_ident;
4029 
4030     // Construct short_branch_version() method.
4031     fprintf(fp_cpp, "// Build short branch version of this instruction\n");
4032     fprintf(fp_cpp, "MachNode *%sNode::short_branch_version(Compile* C) {\n", this->_ident);
4033     // Create the MachNode object
4034     fprintf(fp_cpp, "  %sNode *node = new (C) %sNode();\n", name, name);
4035     if( is_ideal_if() ) {
4036       fprintf(fp_cpp, "  node->_prob = _prob;\n");
4037       fprintf(fp_cpp, "  node->_fcnt = _fcnt;\n");
4038     }
4039     // Fill in the bottom_type where requested
4040     if ( this->captures_bottom_type(AD.globalNames()) ) {
4041       fprintf(fp_cpp, "  node->_bottom_type = bottom_type();\n");
4042     }
4043 
4044     fprintf(fp_cpp, "\n");
4045     // Short branch version must use same node index for access
4046     // through allocator's tables
4047     fprintf(fp_cpp, "  // Copy _idx, inputs and operands to new node\n");
4048     fprintf(fp_cpp, "  fill_new_machnode(node, C);\n");
4049 
4050     // Return result and exit scope
4051     fprintf(fp_cpp, "  return node;\n");
4052     fprintf(fp_cpp, "}\n");
4053     fprintf(fp_cpp,"\n");
4054     return true;
4055   }
4056   return false;
4057 }
4058 
4059 
4060 //---------------------------buildMachNodeGenerator----------------------------
4061 // Build switch to invoke appropriate "new" MachNode for an opcode
4062 void ArchDesc::buildMachNodeGenerator(FILE *fp_cpp) {
4063 
4064   // Build switch to invoke 'new' for a specific MachNode
4065   fprintf(fp_cpp, "\n");
4066   fprintf(fp_cpp, "\n");
4067   fprintf(fp_cpp,
4068           "//------------------------- MachNode Generator ---------------\n");
4069   fprintf(fp_cpp,
4070           "// A switch statement on the dense-packed user-defined type system\n"
4071           "// that invokes 'new' on the corresponding class constructor.\n");
4072   fprintf(fp_cpp, "\n");
4073   fprintf(fp_cpp, "MachNode *State::MachNodeGenerator");
4074   fprintf(fp_cpp, "(int opcode, Compile* C)");
4075   fprintf(fp_cpp, "{\n");
4076   fprintf(fp_cpp, "  switch(opcode) {\n");
4077 
4078   // Provide constructor for all user-defined instructions
4079   _instructions.reset();
4080   int  opIndex = operandFormCount();
4081   InstructForm *inst;
4082   for( ; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
4083     // Ensure that matrule is defined.
4084     if ( inst->_matrule == NULL ) continue;
4085 
4086     int         opcode  = opIndex++;
4087     const char *opClass = inst->_ident;
4088     char       *opType  = NULL;
4089 
4090     // Generate the case statement for this instruction
4091     fprintf(fp_cpp, "  case %s_rule:", opClass);
4092 
4093     // Start local scope
4094     fprintf(fp_cpp, " {\n");
4095     // Generate code to construct the new MachNode
4096     buildMachNode(fp_cpp, inst, "     ");
4097     // Return result and exit scope
4098     fprintf(fp_cpp, "      return node;\n");
4099     fprintf(fp_cpp, "    }\n");
4100   }
4101 
4102   // Generate the default case for switch(opcode)
4103   fprintf(fp_cpp, "  \n");
4104   fprintf(fp_cpp, "  default:\n");
4105   fprintf(fp_cpp, "    fprintf(stderr, \"Default MachNode Generator invoked for: \\n\");\n");
4106   fprintf(fp_cpp, "    fprintf(stderr, \"   opcode = %cd\\n\", opcode);\n", '%');
4107   fprintf(fp_cpp, "    break;\n");
4108   fprintf(fp_cpp, "  };\n");
4109 
4110   // Generate the closing for method Matcher::MachNodeGenerator
4111   fprintf(fp_cpp, "  return NULL;\n");
4112   fprintf(fp_cpp, "}\n");
4113 }
4114 
4115 
4116 //---------------------------buildInstructMatchCheck--------------------------
4117 // Output the method to Matcher which checks whether or not a specific
4118 // instruction has a matching rule for the host architecture.
4119 void ArchDesc::buildInstructMatchCheck(FILE *fp_cpp) const {
4120   fprintf(fp_cpp, "\n\n");
4121   fprintf(fp_cpp, "const bool Matcher::has_match_rule(int opcode) {\n");
4122   fprintf(fp_cpp, "  assert(_last_machine_leaf < opcode && opcode < _last_opcode, \"opcode in range\");\n");
4123   fprintf(fp_cpp, "  return _hasMatchRule[opcode];\n");
4124   fprintf(fp_cpp, "}\n\n");
4125 
4126   fprintf(fp_cpp, "const bool Matcher::_hasMatchRule[_last_opcode] = {\n");
4127   int i;
4128   for (i = 0; i < _last_opcode - 1; i++) {
4129     fprintf(fp_cpp, "    %-5s,  // %s\n",
4130             _has_match_rule[i] ? "true" : "false",
4131             NodeClassNames[i]);
4132   }
4133   fprintf(fp_cpp, "    %-5s   // %s\n",
4134           _has_match_rule[i] ? "true" : "false",
4135           NodeClassNames[i]);
4136   fprintf(fp_cpp, "};\n");
4137 }
4138 
4139 //---------------------------buildFrameMethods---------------------------------
4140 // Output the methods to Matcher which specify frame behavior
4141 void ArchDesc::buildFrameMethods(FILE *fp_cpp) {
4142   fprintf(fp_cpp,"\n\n");
4143   // Stack Direction
4144   fprintf(fp_cpp,"bool Matcher::stack_direction() const { return %s; }\n\n",
4145           _frame->_direction ? "true" : "false");
4146   // Sync Stack Slots
4147   fprintf(fp_cpp,"int Compile::sync_stack_slots() const { return %s; }\n\n",
4148           _frame->_sync_stack_slots);
4149   // Java Stack Alignment
4150   fprintf(fp_cpp,"uint Matcher::stack_alignment_in_bytes() { return %s; }\n\n",
4151           _frame->_alignment);
4152   // Java Return Address Location
4153   fprintf(fp_cpp,"OptoReg::Name Matcher::return_addr() const {");
4154   if (_frame->_return_addr_loc) {
4155     fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
4156             _frame->_return_addr);
4157   }
4158   else {
4159     fprintf(fp_cpp," return OptoReg::stack2reg(%s); }\n\n",
4160             _frame->_return_addr);
4161   }
4162   // Java Stack Slot Preservation
4163   fprintf(fp_cpp,"uint Compile::in_preserve_stack_slots() ");
4164   fprintf(fp_cpp,"{ return %s; }\n\n", _frame->_in_preserve_slots);
4165   // Top Of Stack Slot Preservation, for both Java and C
4166   fprintf(fp_cpp,"uint Compile::out_preserve_stack_slots() ");
4167   fprintf(fp_cpp,"{ return SharedRuntime::out_preserve_stack_slots(); }\n\n");
4168   // varargs C out slots killed
4169   fprintf(fp_cpp,"uint Compile::varargs_C_out_slots_killed() const ");
4170   fprintf(fp_cpp,"{ return %s; }\n\n", _frame->_varargs_C_out_slots_killed);
4171   // Java Argument Position
4172   fprintf(fp_cpp,"void Matcher::calling_convention(BasicType *sig_bt, VMRegPair *regs, uint length, bool is_outgoing) {\n");
4173   fprintf(fp_cpp,"%s\n", _frame->_calling_convention);
4174   fprintf(fp_cpp,"}\n\n");
4175   // Native Argument Position
4176   fprintf(fp_cpp,"void Matcher::c_calling_convention(BasicType *sig_bt, VMRegPair *regs, uint length) {\n");
4177   fprintf(fp_cpp,"%s\n", _frame->_c_calling_convention);
4178   fprintf(fp_cpp,"}\n\n");
4179   // Java Return Value Location
4180   fprintf(fp_cpp,"OptoRegPair Matcher::return_value(uint ideal_reg, bool is_outgoing) {\n");
4181   fprintf(fp_cpp,"%s\n", _frame->_return_value);
4182   fprintf(fp_cpp,"}\n\n");
4183   // Native Return Value Location
4184   fprintf(fp_cpp,"OptoRegPair Matcher::c_return_value(uint ideal_reg, bool is_outgoing) {\n");
4185   fprintf(fp_cpp,"%s\n", _frame->_c_return_value);
4186   fprintf(fp_cpp,"}\n\n");
4187 
4188   // Inline Cache Register, mask definition, and encoding
4189   fprintf(fp_cpp,"OptoReg::Name Matcher::inline_cache_reg() {");
4190   fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
4191           _frame->_inline_cache_reg);
4192   fprintf(fp_cpp,"int Matcher::inline_cache_reg_encode() {");
4193   fprintf(fp_cpp," return _regEncode[inline_cache_reg()]; }\n\n");
4194 
4195   // Interpreter's Method Oop Register, mask definition, and encoding
4196   fprintf(fp_cpp,"OptoReg::Name Matcher::interpreter_method_oop_reg() {");
4197   fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
4198           _frame->_interpreter_method_oop_reg);
4199   fprintf(fp_cpp,"int Matcher::interpreter_method_oop_reg_encode() {");
4200   fprintf(fp_cpp," return _regEncode[interpreter_method_oop_reg()]; }\n\n");
4201 
4202   // Interpreter's Frame Pointer Register, mask definition, and encoding
4203   fprintf(fp_cpp,"OptoReg::Name Matcher::interpreter_frame_pointer_reg() {");
4204   if (_frame->_interpreter_frame_pointer_reg == NULL)
4205     fprintf(fp_cpp," return OptoReg::Bad; }\n\n");
4206   else
4207     fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
4208             _frame->_interpreter_frame_pointer_reg);
4209 
4210   // Frame Pointer definition
4211   /* CNC - I can not contemplate having a different frame pointer between
4212      Java and native code; makes my head hurt to think about it.
4213   fprintf(fp_cpp,"OptoReg::Name Matcher::frame_pointer() const {");
4214   fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
4215           _frame->_frame_pointer);
4216   */
4217   // (Native) Frame Pointer definition
4218   fprintf(fp_cpp,"OptoReg::Name Matcher::c_frame_pointer() const {");
4219   fprintf(fp_cpp," return OptoReg::Name(%s_num); }\n\n",
4220           _frame->_frame_pointer);
4221 
4222   // Number of callee-save + always-save registers for calling convention
4223   fprintf(fp_cpp, "// Number of callee-save + always-save registers\n");
4224   fprintf(fp_cpp, "int  Matcher::number_of_saved_registers() {\n");
4225   RegDef *rdef;
4226   int nof_saved_registers = 0;
4227   _register->reset_RegDefs();
4228   while( (rdef = _register->iter_RegDefs()) != NULL ) {
4229     if( !strcmp(rdef->_callconv, "SOE") ||  !strcmp(rdef->_callconv, "AS") )
4230       ++nof_saved_registers;
4231   }
4232   fprintf(fp_cpp, "  return %d;\n", nof_saved_registers);
4233   fprintf(fp_cpp, "};\n\n");
4234 }
4235 
4236 
4237 
4238 
4239 static int PrintAdlcCisc = 0;
4240 //---------------------------identify_cisc_spilling----------------------------
4241 // Get info for the CISC_oracle and MachNode::cisc_version()
4242 void ArchDesc::identify_cisc_spill_instructions() {
4243 
4244   if (_frame == NULL)
4245     return;
4246 
4247   // Find the user-defined operand for cisc-spilling
4248   if( _frame->_cisc_spilling_operand_name != NULL ) {
4249     const Form *form = _globalNames[_frame->_cisc_spilling_operand_name];
4250     OperandForm *oper = form ? form->is_operand() : NULL;
4251     // Verify the user's suggestion
4252     if( oper != NULL ) {
4253       // Ensure that match field is defined.
4254       if ( oper->_matrule != NULL )  {
4255         MatchRule &mrule = *oper->_matrule;
4256         if( strcmp(mrule._opType,"AddP") == 0 ) {
4257           MatchNode *left = mrule._lChild;
4258           MatchNode *right= mrule._rChild;
4259           if( left != NULL && right != NULL ) {
4260             const Form *left_op  = _globalNames[left->_opType]->is_operand();
4261             const Form *right_op = _globalNames[right->_opType]->is_operand();
4262             if(  (left_op != NULL && right_op != NULL)
4263               && (left_op->interface_type(_globalNames) == Form::register_interface)
4264               && (right_op->interface_type(_globalNames) == Form::constant_interface) ) {
4265               // Successfully verified operand
4266               set_cisc_spill_operand( oper );
4267               if( _cisc_spill_debug ) {
4268                 fprintf(stderr, "\n\nVerified CISC-spill operand %s\n\n", oper->_ident);
4269              }
4270             }
4271           }
4272         }
4273       }
4274     }
4275   }
4276 
4277   if( cisc_spill_operand() != NULL ) {
4278     // N^2 comparison of instructions looking for a cisc-spilling version
4279     _instructions.reset();
4280     InstructForm *instr;
4281     for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) {
4282       // Ensure that match field is defined.
4283       if ( instr->_matrule == NULL )  continue;
4284 
4285       MatchRule &mrule = *instr->_matrule;
4286       Predicate *pred  =  instr->build_predicate();
4287 
4288       // Grab the machine type of the operand
4289       const char *rootOp = instr->_ident;
4290       mrule._machType    = rootOp;
4291 
4292       // Find result type for match
4293       const char *result = instr->reduce_result();
4294 
4295       if( PrintAdlcCisc ) fprintf(stderr, "  new instruction %s \n", instr->_ident ? instr->_ident : " ");
4296       bool  found_cisc_alternate = false;
4297       _instructions.reset2();
4298       InstructForm *instr2;
4299       for( ; !found_cisc_alternate && (instr2 = (InstructForm*)_instructions.iter2()) != NULL; ) {
4300         // Ensure that match field is defined.
4301         if( PrintAdlcCisc ) fprintf(stderr, "  instr2 == %s \n", instr2->_ident ? instr2->_ident : " ");
4302         if ( instr2->_matrule != NULL
4303             && (instr != instr2 )                // Skip self
4304             && (instr2->reduce_result() != NULL) // want same result
4305             && (strcmp(result, instr2->reduce_result()) == 0)) {
4306           MatchRule &mrule2 = *instr2->_matrule;
4307           Predicate *pred2  =  instr2->build_predicate();
4308           found_cisc_alternate = instr->cisc_spills_to(*this, instr2);
4309         }
4310       }
4311     }
4312   }
4313 }
4314 
4315 //---------------------------build_cisc_spilling-------------------------------
4316 // Get info for the CISC_oracle and MachNode::cisc_version()
4317 void ArchDesc::build_cisc_spill_instructions(FILE *fp_hpp, FILE *fp_cpp) {
4318   // Output the table for cisc spilling
4319   fprintf(fp_cpp, "//  The following instructions can cisc-spill\n");
4320   _instructions.reset();
4321   InstructForm *inst = NULL;
4322   for(; (inst = (InstructForm*)_instructions.iter()) != NULL; ) {
4323     // Ensure this is a machine-world instruction
4324     if ( inst->ideal_only() )  continue;
4325     const char *inst_name = inst->_ident;
4326     int   operand   = inst->cisc_spill_operand();
4327     if( operand != AdlcVMDeps::Not_cisc_spillable ) {
4328       InstructForm *inst2 = inst->cisc_spill_alternate();
4329       fprintf(fp_cpp, "//  %s can cisc-spill operand %d to %s\n", inst->_ident, operand, inst2->_ident);
4330     }
4331   }
4332   fprintf(fp_cpp, "\n\n");
4333 }
4334 
4335 //---------------------------identify_short_branches----------------------------
4336 // Get info for our short branch replacement oracle.
4337 void ArchDesc::identify_short_branches() {
4338   // Walk over all instructions, checking to see if they match a short
4339   // branching alternate.
4340   _instructions.reset();
4341   InstructForm *instr;
4342   while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
4343     // The instruction must have a match rule.
4344     if (instr->_matrule != NULL &&
4345         instr->is_short_branch()) {
4346 
4347       _instructions.reset2();
4348       InstructForm *instr2;
4349       while( (instr2 = (InstructForm*)_instructions.iter2()) != NULL ) {
4350         instr2->check_branch_variant(*this, instr);
4351       }
4352     }
4353   }
4354 }
4355 
4356 
4357 //---------------------------identify_unique_operands---------------------------
4358 // Identify unique operands.
4359 void ArchDesc::identify_unique_operands() {
4360   // Walk over all instructions.
4361   _instructions.reset();
4362   InstructForm *instr;
4363   while( (instr = (InstructForm*)_instructions.iter()) != NULL ) {
4364     // Ensure this is a machine-world instruction
4365     if (!instr->ideal_only()) {
4366       instr->set_unique_opnds();
4367     }
4368   }
4369 }