1 /*
   2  * Copyright (c) 1997, 2009, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 // MAIN.CPP - Entry point for the Architecture Description Language Compiler
  26 #include "adlc.hpp"
  27 
  28 //------------------------------Prototypes-------------------------------------
  29 static void  usage(ArchDesc& AD);          // Print usage message and exit
  30 static char *strip_ext(char *fname);       // Strip off name extension
  31 static char *base_plus_suffix(const char* base, const char *suffix);// New concatenated string
  32 static char *prefix_plus_base_plus_suffix(const char* prefix, const char* base, const char *suffix);// New concatenated string
  33 static int get_legal_text(FileBuff &fbuf, char **legal_text); // Get pointer to legal text
  34 
  35 ArchDesc* globalAD = NULL;      // global reference to Architecture Description object
  36 
  37 //------------------------------main-------------------------------------------
  38 int main(int argc, char *argv[])
  39 {
  40   ArchDesc      AD;             // Architecture Description object
  41   globalAD = &AD;
  42 
  43   // ResourceMark  mark;
  44   ADLParser    *ADL_Parse;      // ADL Parser object to parse AD file
  45 
  46   // Check for proper arguments
  47   if( argc == 1 ) usage(AD);    // No arguments?  Then print usage
  48 
  49   // Read command line arguments and file names
  50   for( int i = 1; i < argc; i++ ) { // For all arguments
  51     register char *s = argv[i]; // Get option/filename
  52 
  53     if( *s++ == '-' ) {         // It's a flag? (not a filename)
  54       if( !*s ) {               // Stand-alone `-' means stdin
  55         //********** INSERT CODE HERE **********
  56       } else while (*s != '\0') { // While have flags on option
  57         switch (*s++) {         // Handle flag
  58         case 'd':               // Debug flag
  59           AD._dfa_debug += 1;   // Set Debug Flag
  60           break;
  61         case 'g':               // Debug ad location flag
  62           AD._adlocation_debug += 1;       // Set Debug ad location Flag
  63           break;
  64         case 'o':               // No Output Flag
  65           AD._no_output ^= 1;   // Toggle no_output flag
  66           break;
  67         case 'q':               // Quiet Mode Flag
  68           AD._quiet_mode ^= 1;  // Toggle quiet_mode flag
  69           break;
  70         case 'w':               // Disable Warnings Flag
  71           AD._disable_warnings ^= 1; // Toggle disable_warnings flag
  72           break;
  73         case 'T':               // Option to make DFA as many subroutine calls.
  74           AD._dfa_small += 1;   // Set Mode Flag
  75           break;
  76         case 'c': {             // Set C++ Output file name
  77           AD._CPP_file._name = s;
  78           const char *base = strip_ext(strdup(s));
  79           AD._CPP_CLONE_file._name    = base_plus_suffix(base,"_clone.cpp");
  80           AD._CPP_EXPAND_file._name   = base_plus_suffix(base,"_expand.cpp");
  81           AD._CPP_FORMAT_file._name   = base_plus_suffix(base,"_format.cpp");
  82           AD._CPP_GEN_file._name      = base_plus_suffix(base,"_gen.cpp");
  83           AD._CPP_MISC_file._name     = base_plus_suffix(base,"_misc.cpp");
  84           AD._CPP_PEEPHOLE_file._name = base_plus_suffix(base,"_peephole.cpp");
  85           AD._CPP_PIPELINE_file._name = base_plus_suffix(base,"_pipeline.cpp");
  86           s += strlen(s);
  87           break;
  88         }
  89         case 'h':               // Set C++ Output file name
  90           AD._HPP_file._name = s; s += strlen(s);
  91           break;
  92         case 'v':               // Set C++ Output file name
  93           AD._VM_file._name = s; s += strlen(s);
  94           break;
  95         case 'a':               // Set C++ Output file name
  96           AD._DFA_file._name = s;
  97           AD._bug_file._name = s;
  98           s += strlen(s);
  99           break;
 100         case '#':               // Special internal debug flag
 101           AD._adl_debug++;      // Increment internal debug level
 102           break;
 103         case 's':               // Output which instructions are cisc-spillable
 104           AD._cisc_spill_debug = true;
 105           break;
 106         case 'D':               // Flag Definition
 107           {
 108             char* flag = s;
 109             s += strlen(s);
 110             char* def = strchr(flag, '=');
 111             if (def == NULL)  def = (char*)"1";
 112             else              *def++ = '\0';
 113             AD.set_preproc_def(flag, def);
 114           }
 115           break;
 116         case 'U':               // Flag Un-Definition
 117           {
 118             char* flag = s;
 119             s += strlen(s);
 120             AD.set_preproc_def(flag, NULL);
 121           }
 122           break;
 123         default:                // Unknown option
 124           usage(AD);            // So print usage and exit
 125         }                       // End of switch on options...
 126       }                         // End of while have options...
 127 
 128     } else {                    // Not an option; must be a filename
 129       AD._ADL_file._name = argv[i]; // Set the input filename
 130 
 131       // // Files for storage, based on input file name
 132       const char *base = strip_ext(strdup(argv[i]));
 133       char       *temp = base_plus_suffix("dfa_",base);
 134       AD._DFA_file._name = base_plus_suffix(temp,".cpp");
 135       delete temp;
 136       temp = base_plus_suffix("ad_",base);
 137       AD._CPP_file._name          = base_plus_suffix(temp,".cpp");
 138       AD._CPP_CLONE_file._name    = base_plus_suffix(temp,"_clone.cpp");
 139       AD._CPP_EXPAND_file._name   = base_plus_suffix(temp,"_expand.cpp");
 140       AD._CPP_FORMAT_file._name   = base_plus_suffix(temp,"_format.cpp");
 141       AD._CPP_GEN_file._name      = base_plus_suffix(temp,"_gen.cpp");
 142       AD._CPP_MISC_file._name     = base_plus_suffix(temp,"_misc.cpp");
 143       AD._CPP_PEEPHOLE_file._name = base_plus_suffix(temp,"_peephole.cpp");
 144       AD._CPP_PIPELINE_file._name = base_plus_suffix(temp,"_pipeline.cpp");
 145       AD._HPP_file._name = base_plus_suffix(temp,".hpp");
 146       delete temp;
 147       temp = base_plus_suffix("adGlobals_",base);
 148       AD._VM_file._name = base_plus_suffix(temp,".hpp");
 149       delete temp;
 150       temp = base_plus_suffix("bugs_",base);
 151       AD._bug_file._name = base_plus_suffix(temp,".out");
 152       delete temp;
 153     }                           // End of files vs options...
 154   }                             // End of while have command line arguments
 155 
 156   // Open files used to store the matcher and its components
 157   if (AD.open_files() == 0) return 1; // Open all input/output files
 158 
 159   // Build the File Buffer, Parse the input, & Generate Code
 160   FileBuff  ADL_Buf(&AD._ADL_file, AD); // Create a file buffer for input file
 161 
 162   // Get pointer to legal text at the beginning of AD file.
 163   // It will be used in generated ad files.
 164   char* legal_text;
 165   int legal_sz = get_legal_text(ADL_Buf, &legal_text);
 166 
 167   ADL_Parse = new ADLParser(ADL_Buf, AD); // Create a parser to parse the buffer
 168   ADL_Parse->parse();           // Parse buffer & build description lists
 169 
 170   if( AD._dfa_debug >= 1 ) {    // For higher debug settings, print dump
 171     AD.dump();
 172   }
 173 
 174   delete ADL_Parse;             // Delete parser
 175 
 176   // Verify that the results of the parse are consistent
 177   AD.verify();
 178 
 179   // Prepare to generate the result files:
 180   AD.generateMatchLists();
 181   AD.identify_unique_operands();
 182   AD.identify_cisc_spill_instructions();
 183   AD.identify_short_branches();
 184   // Make sure every file starts with a copyright:
 185   AD.addSunCopyright(legal_text, legal_sz, AD._HPP_file._fp);           // .hpp
 186   AD.addSunCopyright(legal_text, legal_sz, AD._CPP_file._fp);           // .cpp
 187   AD.addSunCopyright(legal_text, legal_sz, AD._CPP_CLONE_file._fp);     // .cpp
 188   AD.addSunCopyright(legal_text, legal_sz, AD._CPP_EXPAND_file._fp);    // .cpp
 189   AD.addSunCopyright(legal_text, legal_sz, AD._CPP_FORMAT_file._fp);    // .cpp
 190   AD.addSunCopyright(legal_text, legal_sz, AD._CPP_GEN_file._fp);       // .cpp
 191   AD.addSunCopyright(legal_text, legal_sz, AD._CPP_MISC_file._fp);      // .cpp
 192   AD.addSunCopyright(legal_text, legal_sz, AD._CPP_PEEPHOLE_file._fp);  // .cpp
 193   AD.addSunCopyright(legal_text, legal_sz, AD._CPP_PIPELINE_file._fp);  // .cpp
 194   AD.addSunCopyright(legal_text, legal_sz, AD._VM_file._fp);            // .hpp
 195   AD.addSunCopyright(legal_text, legal_sz, AD._DFA_file._fp);           // .cpp
 196   // Make sure each .cpp file starts with include lines:
 197   // files declaring and defining generators for Mach* Objects (hpp,cpp)
 198   AD.machineDependentIncludes(AD._CPP_file);      // .cpp
 199   AD.machineDependentIncludes(AD._CPP_CLONE_file);     // .cpp
 200   AD.machineDependentIncludes(AD._CPP_EXPAND_file);    // .cpp
 201   AD.machineDependentIncludes(AD._CPP_FORMAT_file);    // .cpp
 202   AD.machineDependentIncludes(AD._CPP_GEN_file);       // .cpp
 203   AD.machineDependentIncludes(AD._CPP_MISC_file);      // .cpp
 204   AD.machineDependentIncludes(AD._CPP_PEEPHOLE_file);  // .cpp
 205   AD.machineDependentIncludes(AD._CPP_PIPELINE_file);  // .cpp
 206   // Generate the result files:
 207   // enumerations, class definitions, object generators, and the DFA
 208   // file containing enumeration of machine operands & instructions (hpp)
 209   AD.addPreHeaderBlocks(AD._HPP_file._fp);        // .hpp
 210   AD.buildMachOperEnum(AD._HPP_file._fp);         // .hpp
 211   AD.buildMachOpcodesEnum(AD._HPP_file._fp);      // .hpp
 212   AD.buildMachRegisterNumbers(AD._VM_file._fp);   // VM file
 213   AD.buildMachRegisterEncodes(AD._HPP_file._fp);  // .hpp file
 214   AD.declareRegSizes(AD._HPP_file._fp);           // .hpp
 215   AD.build_pipeline_enums(AD._HPP_file._fp);      // .hpp
 216   // output definition of class "State"
 217   AD.defineStateClass(AD._HPP_file._fp);          // .hpp
 218   // file declaring the Mach* classes derived from MachOper and MachNode
 219   AD.declareClasses(AD._HPP_file._fp);
 220   // declare and define maps: in the .hpp and .cpp files respectively
 221   AD.addSourceBlocks(AD._CPP_file._fp);           // .cpp
 222   AD.addHeaderBlocks(AD._HPP_file._fp);           // .hpp
 223   AD.buildReduceMaps(AD._HPP_file._fp, AD._CPP_file._fp);
 224   AD.buildMustCloneMap(AD._HPP_file._fp, AD._CPP_file._fp);
 225   // build CISC_spilling oracle and MachNode::cisc_spill() methods
 226   AD.build_cisc_spill_instructions(AD._HPP_file._fp, AD._CPP_file._fp);
 227   // define methods for machine dependent State, MachOper, and MachNode classes
 228   AD.defineClasses(AD._CPP_file._fp);
 229   AD.buildMachOperGenerator(AD._CPP_GEN_file._fp);// .cpp
 230   AD.buildMachNodeGenerator(AD._CPP_GEN_file._fp);// .cpp
 231   // define methods for machine dependent instruction matching
 232   AD.buildInstructMatchCheck(AD._CPP_file._fp);  // .cpp
 233   // define methods for machine dependent frame management
 234   AD.buildFrameMethods(AD._CPP_file._fp);         // .cpp
 235 
 236   // do this last:
 237   AD.addPreprocessorChecks(AD._CPP_file._fp);     // .cpp
 238   AD.addPreprocessorChecks(AD._CPP_CLONE_file._fp);     // .cpp
 239   AD.addPreprocessorChecks(AD._CPP_EXPAND_file._fp);    // .cpp
 240   AD.addPreprocessorChecks(AD._CPP_FORMAT_file._fp);    // .cpp
 241   AD.addPreprocessorChecks(AD._CPP_GEN_file._fp);       // .cpp
 242   AD.addPreprocessorChecks(AD._CPP_MISC_file._fp);      // .cpp
 243   AD.addPreprocessorChecks(AD._CPP_PEEPHOLE_file._fp);  // .cpp
 244   AD.addPreprocessorChecks(AD._CPP_PIPELINE_file._fp);  // .cpp
 245 
 246   // define the finite automata that selects lowest cost production
 247   AD.machineDependentIncludes(AD._DFA_file);      // .cpp
 248   AD.buildDFA(AD._DFA_file._fp);
 249 
 250   AD.close_files(0);               // Close all input/output files
 251 
 252   // Final printout and statistics
 253   // cout << program;
 254 
 255   if( AD._dfa_debug & 2 ) {    // For higher debug settings, print timing info
 256     //    Timer t_stop;
 257     //    Timer t_total = t_stop - t_start; // Total running time
 258     //    cerr << "\n---Architecture Description Totals---\n";
 259     //    cerr << ", Total lines: " << TotalLines;
 260     //    float l = TotalLines;
 261     //    cerr << "\nTotal Compilation Time: " << t_total << "\n";
 262     //    float ft = (float)t_total;
 263     //    if( ft > 0.0 ) fprintf(stderr,"Lines/sec: %#5.2f\n", l/ft);
 264   }
 265   return (AD._syntax_errs + AD._semantic_errs + AD._internal_errs); // Bye Bye!!
 266 }
 267 
 268 //------------------------------usage------------------------------------------
 269 static void usage(ArchDesc& AD)
 270 {
 271   printf("Architecture Description Language Compiler\n\n");
 272   printf("Usage: adl [-doqw] [-Dflag[=def]] [-Uflag] [-cFILENAME] [-hFILENAME] [-aDFAFILE] ADLFILE\n");
 273   printf(" d  produce DFA debugging info\n");
 274   printf(" o  no output produced, syntax and semantic checking only\n");
 275   printf(" q  quiet mode, supresses all non-essential messages\n");
 276   printf(" w  suppress warning messages\n");
 277   printf(" c  specify CPP file name (default: %s)\n", AD._CPP_file._name);
 278   printf(" h  specify HPP file name (default: %s)\n", AD._HPP_file._name);
 279   printf(" a  specify DFA output file name\n");
 280   printf("\n");
 281 }
 282 
 283 //------------------------------open_file------------------------------------
 284 int ArchDesc::open_file(bool required, ADLFILE & ADF, const char *action)
 285 {
 286   if (required &&
 287       (ADF._fp = fopen(ADF._name, action)) == NULL) {
 288     printf("ERROR: Cannot open file for %s: %s\n", action, ADF._name);
 289     close_files(1);
 290     return 0;
 291   }
 292   return 1;
 293 }
 294 
 295 //------------------------------open_files-------------------------------------
 296 int ArchDesc::open_files(void)
 297 {
 298   if (_ADL_file._name == NULL)
 299   { printf("ERROR: No ADL input file specified\n"); return 0; }
 300 
 301   if (!open_file(true       , _ADL_file, "r"))          { return 0; }
 302   if (!open_file(!_no_output, _DFA_file, "w"))          { return 0; }
 303   if (!open_file(!_no_output, _HPP_file, "w"))          { return 0; }
 304   if (!open_file(!_no_output, _CPP_file, "w"))          { return 0; }
 305   if (!open_file(!_no_output, _CPP_CLONE_file, "w"))    { return 0; }
 306   if (!open_file(!_no_output, _CPP_EXPAND_file, "w"))   { return 0; }
 307   if (!open_file(!_no_output, _CPP_FORMAT_file, "w"))   { return 0; }
 308   if (!open_file(!_no_output, _CPP_GEN_file, "w"))      { return 0; }
 309   if (!open_file(!_no_output, _CPP_MISC_file, "w"))     { return 0; }
 310   if (!open_file(!_no_output, _CPP_PEEPHOLE_file, "w")) { return 0; }
 311   if (!open_file(!_no_output, _CPP_PIPELINE_file, "w")) { return 0; }
 312   if (!open_file(!_no_output, _VM_file , "w"))          { return 0; }
 313   if (!open_file(_dfa_debug != 0, _bug_file, "w"))    { return 0; }
 314 
 315   return 1;
 316 }
 317 
 318 //------------------------------close_file------------------------------------
 319 void ArchDesc::close_file(int delete_out, ADLFILE& ADF)
 320 {
 321   if (ADF._fp) {
 322     fclose(ADF._fp);
 323     if (delete_out) remove(ADF._name);
 324   }
 325 }
 326 
 327 //------------------------------close_files------------------------------------
 328 void ArchDesc::close_files(int delete_out)
 329 {
 330   if (_ADL_file._fp) fclose(_ADL_file._fp);
 331 
 332   close_file(delete_out, _CPP_file);
 333   close_file(delete_out, _CPP_CLONE_file);
 334   close_file(delete_out, _CPP_EXPAND_file);
 335   close_file(delete_out, _CPP_FORMAT_file);
 336   close_file(delete_out, _CPP_GEN_file);
 337   close_file(delete_out, _CPP_MISC_file);
 338   close_file(delete_out, _CPP_PEEPHOLE_file);
 339   close_file(delete_out, _CPP_PIPELINE_file);
 340   close_file(delete_out, _HPP_file);
 341   close_file(delete_out, _DFA_file);
 342   close_file(delete_out, _bug_file);
 343 
 344   if (!_quiet_mode) {
 345     printf("\n");
 346     if (_no_output || delete_out) {
 347       if (_ADL_file._name) printf("%s: ", _ADL_file._name);
 348       printf("No output produced");
 349     }
 350     else {
 351       if (_ADL_file._name) printf("%s --> ", _ADL_file._name);
 352       printf("%s, %s, %s, %s, %s, %s, %s, %s, %s, %s",
 353              _CPP_file._name,
 354              _CPP_CLONE_file._name,
 355              _CPP_EXPAND_file._name,
 356              _CPP_FORMAT_file._name,
 357              _CPP_GEN_file._name,
 358              _CPP_MISC_file._name,
 359              _CPP_PEEPHOLE_file._name,
 360              _CPP_PIPELINE_file._name,
 361              _HPP_file._name,
 362              _DFA_file._name);
 363     }
 364     printf("\n");
 365   }
 366 }
 367 
 368 //------------------------------strip_ext--------------------------------------
 369 static char *strip_ext(char *fname)
 370 {
 371   char *ep;
 372 
 373   if (fname) {
 374     ep = fname + strlen(fname) - 1; // start at last character and look for '.'
 375     while (ep >= fname && *ep != '.') --ep;
 376     if (*ep == '.')     *ep = '\0'; // truncate string at '.'
 377   }
 378   return fname;
 379 }
 380 
 381 //------------------------------strip_path_and_ext------------------------------
 382 static char *strip_path_and_ext(char *fname)
 383 {
 384   char *ep;
 385   char *sp;
 386 
 387   if (fname) {
 388     for (sp = fname; *sp; sp++)
 389       if (*sp == '/')  fname = sp+1;
 390     ep = fname;                    // start at first character and look for '.'
 391     while (ep <= (fname + strlen(fname) - 1) && *ep != '.') ep++;
 392     if (*ep == '.')     *ep = '\0'; // truncate string at '.'
 393   }
 394   return fname;
 395 }
 396 
 397 //------------------------------base_plus_suffix-------------------------------
 398 // New concatenated string
 399 static char *base_plus_suffix(const char* base, const char *suffix)
 400 {
 401   int len = (int)strlen(base) + (int)strlen(suffix) + 1;
 402 
 403   char* fname = new char[len];
 404   sprintf(fname,"%s%s",base,suffix);
 405   return fname;
 406 }
 407 
 408 
 409 //------------------------------prefix_plus_base_plus_suffix-------------------
 410 // New concatenated string
 411 static char *prefix_plus_base_plus_suffix(const char* prefix, const char* base, const char *suffix)
 412 {
 413   int len = (int)strlen(prefix) + (int)strlen(base) + (int)strlen(suffix) + 1;
 414 
 415   char* fname = new char[len];
 416   sprintf(fname,"%s%s%s",prefix,base,suffix);
 417   return fname;
 418 }
 419 
 420 //------------------------------get_legal_text---------------------------------
 421 // Get pointer to legal text at the beginning of AD file.
 422 // This code assumes that a legal text starts at the beginning of .ad files,
 423 // is commented by "//" at each line and ends with empty line.
 424 //
 425 int get_legal_text(FileBuff &fbuf, char **legal_text)
 426 {
 427   char* legal_start = fbuf.get_line();
 428   assert(legal_start[0] == '/' && legal_start[1] == '/', "Incorrect header of AD file");
 429   char* legal_end = fbuf.get_line();
 430   assert(strncmp(legal_end, "// Copyright", 12) == 0, "Incorrect header of AD file");
 431   while(legal_end[0] == '/' && legal_end[1] == '/') {
 432     legal_end = fbuf.get_line();
 433   }
 434   *legal_text = legal_start;
 435   return (int) (legal_end - legal_start);
 436 }
 437 
 438 // VS2005 has its own definition, identical to this one.
 439 #if !defined(_WIN32) || defined(_WIN64) || _MSC_VER < 1400
 440 void *operator new( size_t size, int, const char *, int ) {
 441   return ::operator new( size );
 442 }
 443 #endif