src/share/vm/adlc/output_c.cpp

Tue, 16 Aug 2011 11:53:57 -0700

author
kvn
date
Tue, 16 Aug 2011 11:53:57 -0700
changeset 3051
11211f7cb5a0
parent 3037
3d42f82cd811
child 3310
6729bbc1fcd6
permissions
-rw-r--r--

7079317: Incorrect branch's destination block in PrintoOptoAssembly output
Summary: save/restore label and block in scratch_emit_size()
Reviewed-by: never

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

mercurial