src/share/vm/adlc/output_c.cpp

Thu, 27 Dec 2018 11:43:33 +0800

author
aoqi
date
Thu, 27 Dec 2018 11:43:33 +0800
changeset 9448
73d689add964
parent 9333
2fccf735a116
parent 9138
b56ab8e56604
child 9852
70aa912cebe5
permissions
-rw-r--r--

Merge

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

mercurial