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