src/share/vm/adlc/output_c.cpp

Tue, 07 Jan 2014 14:26:12 -0800

author
twisti
date
Tue, 07 Jan 2014 14:26:12 -0800
changeset 9846
9003f35baaa0
parent 9333
2fccf735a116
child 9852
70aa912cebe5
permissions
-rw-r--r--

8022263: use same Clang warnings on BSD as on Linux
Reviewed-by: kvn, iveresov

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

mercurial