src/share/vm/adlc/output_c.cpp

Mon, 25 Jun 2012 21:33:35 -0400

author
coleenp
date
Mon, 25 Jun 2012 21:33:35 -0400
changeset 3875
246d977b51f2
parent 3317
db2e64ca2d5a
child 4037
da91efe96a93
permissions
-rw-r--r--

7178670: runtime/7158800/BadUtf8.java fails in SymbolTable::rehash_table
Summary: Cannot delete _buckets and HashtableEntries in shared space (CDS)
Reviewed-by: acorn, kvn, dlong, dcubed, kamg

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

mercurial