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