Exemplo n.º 1
0
int main(int argc, char * argv[])
{
  // This flag can skip insertion of XOMP_init() and XOMP_terminate(), both of which are defined in libxomp.a
  // But somehow nvcc cannot link the entire libxomp.a with the cuda object file
  // TODO: ultimate solution is to outline all CUDA code into a separate file and keep the original file type intact
  OmpSupport::enable_accelerator = true;

  SgProject *project = frontend (argc, argv);


  //TODO: turn this back on once blockDim.x * blockIdx.x + threadIdx.x is built properly in omp_lowering.cpp
  //  AstTests::runAllTests(project);

  // change .c suffix to .cu suffix
  // We only process one single input file at a time
  ROSE_ASSERT (project->get_fileList().size() ==1);
  SgFile * cur_file = project->get_fileList()[0];

  string orig_name = cur_file->get_file_info()->get_filenameString();
  string file_suffix = StringUtility::fileNameSuffix(orig_name);
  // We only allow C file to be compatible with nvcc CUDA compiler
  ROSE_ASSERT (CommandlineProcessing::isCFileNameSuffix(file_suffix));
  orig_name = StringUtility::stripPathFromFileName(orig_name);
  string naked_name = StringUtility::stripFileSuffixFromFileName(orig_name);
  cur_file->set_unparse_output_filename("rose_"+naked_name+".cu");

  return backend(project);
}
Exemplo n.º 2
0
//! A test main program 
int main ( int argc, char * argv[] )
{
  std::vector <std::string> argvList (argv, argv + argc);
 
  // turn on OpenMP parsing support for device() map (a[][] dist_data()) 
  argvList.push_back("-rose:openmp:parse_only");

  SgProject* project = frontend(argvList); //frontendConstantFolding);
  ROSE_ASSERT(project != NULL);

  // Assuming single input file for this prototype
  ROSE_ASSERT (project->get_fileList().size() ==1);
  SgFile * cur_file = project->get_fileList()[0];

  SgSourceFile* sfile = isSgSourceFile(cur_file);
  
  setupMPIInit (sfile);
  setupMPIFinalize (sfile);

#if 0 
   // old V 0.1
  std::vector <MPI_PragmaAttribute*> pragma_attribute_list;
  // Parsing all relevant pragmas, generate MPI_Pragma_Attribute_List.
  parsePragmas (sfile, pragma_attribute_list);
  translatePragmas (pragma_attribute_list);
#else
  // newer V 0.2 
  lower_xomp (sfile);
#endif

  AstTests::runAllTests(project);
  return backend(project);

//  return 0;
}
int
main ( int argc, char * argv[] )
   {
  // Initialize and check compatibility. See Rose::initialize
     ROSE_INITIALIZE;

     vector<string> argvList(argv, argv + argc);

     SgProject* project = NULL;

     bool removeCommandOption = true;
     string pathToSkip;

  // The specified path string will be put into "skipPathString" and then the option will be removed
     if ( CommandlineProcessing::isOptionWithParameter(argvList,"-skipFile:","(path)",pathToSkip,removeCommandOption) )
        {
          printf ("Skip file containing path = %s \n",pathToSkip.c_str());

       // Builds SgProject with valid but empty SgFile objects, but with all command line processing
       // done. The frontend can then be invoked conditionally for each SgFile object.
          project = frontendShell(argvList);

       // Loop over all files in the SgProject (and call the frontend on a selected subset)
          SgFilePtrList::iterator fileIterator = project->get_fileList().begin();
          while (fileIterator != project->get_fileList().end())
             {
               string filename = (*fileIterator)->get_sourceFileNameWithPath();

            // Skip processing of files from a specific directory
            // If there is a match between the path and any part of the filename then skip processing this file
               if (filename.find(pathToSkip) != string::npos)
                  {
                    printf ("Skipping call to the frontend for this file (%s) \n",filename.c_str());
                  }
                 else
                  {
                 // Call the front-end (which will internally call EDG).
                 // Note: The commandline can be reset by using set_originalCommandLineArgumentList().
                    int EDG_FrontEndErrorCode = (*fileIterator)->callFrontEnd();

                 // Warnings from EDG processing are OK, but not errors (EDG detail)
                    ROSE_ASSERT (EDG_FrontEndErrorCode <= 3);
                  }

            // increment the file list iterator
               fileIterator++;
             }
        }
       else
        {
       // This call the frontend automatically for all source files on the command line
          project = frontend(argvList);
        }

  // Call the backend, where files were not processed the original file will be compiled
  // directly by the backend (vendor) compiler. The SgFile objects here would also be 
  // looped over and unparsed and or compiled separately.
     return backend(project);
   }
Exemplo n.º 4
0
int main(int argc, char * argv[])
{
  SgProject *project = frontend (argc, argv);

  // Generate a file handle from the first file of the project
  abstract_node* file_node= buildroseNode((project->get_fileList())[0]);
  abstract_handle* handle0 = new abstract_handle(file_node);
  cout<<"Created a file handle:\n"<<handle0->toString()<<endl<<endl;;

  //Create a handle to a namespace given its name and parent handle 
  string input1="NamespaceDeclarationStatement<name,space1>";
  abstract_handle* handle1 = new abstract_handle(handle0,input1);
  cout<<"Created a handle:\n"<<handle1->toString()<<endl<<endl;
  cout<<"It points to:\n"<<handle1->getNode()->toString()<<endl<<endl;

  // Create a handle within the file, given a string specifying  
  // its construct type (class declaration) and source position 
  string input="ClassDeclaration<position,4.3-9.2>";
  abstract_handle* handle2 = new abstract_handle(handle0,input);

  cout<<"Created a handle:\n"<<handle2->toString()<<endl<<endl;
  cout<<"It points to:\n"<<handle2->getNode()->toString()<<endl<<endl;;

  // find the second function declaration within handle2
  abstract_handle handle3(handle2,"FunctionDeclaration<numbering,2>");

  cout<<"Created a handle:\n"<<handle3.toString()<<endl<<endl;
  cout<<"It points to:\n"<<handle3.getNode()->toString()<<endl;

// Generate source code from AST and call the vendor's compiler
  return backend(project);
}
Exemplo n.º 5
0
Arquivo: tilek.cpp Projeto: 8l/rose
int main(int argc, char ** argv) {
  std::vector<std::string> args(argv, argv + argc);

#if defined(TILEK_ACCELERATOR)
#  if defined(TILEK_TARGET_OPENCL)
  args.push_back("-DSKIP_OPENCL_SPECIFIC_DEFINITION");
#  endif
#endif

  SgProject * project = new SgProject(args);
  assert(project->numberOfFiles() == 1);

  SgSourceFile * source_file = isSgSourceFile(project->get_fileList()[0]);
  assert(source_file != NULL);

  std::string filename = source_file->get_sourceFileNameWithoutPath();
  std::string basename = filename.substr(0, filename.find_last_of('.'));

  KLT::DLX::Compiler< ::DLX::TileK::language_t, ::KLT::TileK::Generator> compiler(project, KLT_PATH, TILEK_PATH, basename);

//  MFB::api_t * api = compiler.getDriver().getAPI();
//  dump_api(api);

  compiler.compile(project);

  project->unparse();

  return 0;
}
Exemplo n.º 6
0
int main(int argc, char * argv[])
{
  // This flag can skip insertion of XOMP_init() and XOMP_terminate(), both of which are defined in libxomp.a
  // But somehow nvcc cannot link the entire libxomp.a with the cuda object file
  // TODO: ultimate solution is to outline all CUDA code into a separate file and keep the original file type intact
  OmpSupport::enable_accelerator = true;
  OmpSupport::useDDE = true; // using Device Data Environment to manage data on GPUs

  vector<string> argvList(argv, argv + argc);

   // -rose:openmp:nodde to turn off the use of DDE runtime
   // This option does not work with collapse() now. It is only for debugging and seeing old code only
  if(CommandlineProcessing::isOption (argvList,
        "-rose:openmp:",
        "nodde",
        true) ||
  CommandlineProcessing::isOption (argvList,
        "--rose:openmp:",
        "nodde",
        true))
 
  {
    OmpSupport::useDDE = false;
    cout<<"OpenMP Lowering is set to turn off the use of DDE (Device Data Environment) functions ..."<<endl;
  }

  SgProject *project = frontend (argvList);


  //TODO: turn this back on once blockDim.x * blockIdx.x + threadIdx.x is built properly in omp_lowering.cpp
  //  AstTests::runAllTests(project);

  // change .c suffix to .cu suffix
  // We only process one single input file at a time
  ROSE_ASSERT (project->get_fileList().size() ==1);
  SgFile * cur_file = project->get_fileList()[0];

  string orig_name = cur_file->get_file_info()->get_filenameString();
  string file_suffix = StringUtility::fileNameSuffix(orig_name);
  // We only allow C file to be compatible with nvcc CUDA compiler
  //ROSE_ASSERT (CommandlineProcessing::isCFileNameSuffix(file_suffix));
  orig_name = StringUtility::stripPathFromFileName(orig_name);
  string naked_name = StringUtility::stripFileSuffixFromFileName(orig_name);
  cur_file->set_unparse_output_filename("rose_"+naked_name+".cu");

  return backend(project);
}
Exemplo n.º 7
0
int
main( int argc, char * argv[] )
   {
  // Introduces tracking of performance of ROSE at the top most level.
     TimingPerformance timer ("AST translation (main): time (sec) = ",true);

  // Build a vector of strings to represent the command line arguments.
     std::vector<std::string> sourceCommandline = std::vector<std::string>(argv, argv + argc);
     sourceCommandline.push_back("-rose:unparse_tokens");

     SgProject* project = frontend(sourceCommandline);

     AstTests::runAllTests(project);

  // Evaluate the number of tokens generated for each file on the command line.
     SgFilePtrList & fileList = project->get_fileList();
     for (size_t i=0; i < fileList.size(); i++)
        {
          SgSourceFile* sourceFile = isSgSourceFile(fileList[i]);
          if (sourceFile != NULL)
             {
               size_t numberOfTokens = sourceFile->get_token_list().size();
               printf ("Number of tokens in file %s = %zu \n",sourceFile->get_sourceFileNameWithPath().c_str(),numberOfTokens);
               if (numberOfTokens == 0)
                  {
                 // We output an error, but since this test is only presently valid for fortran files it is not serious.
                    if (sourceFile->get_Fortran_only() == true)
                       {
                         printf ("Warning: numberOfTokens in file equal zero (could be an error). \n");
                       }
                      else
                       {
                         printf ("Warning: token evaluation only valid for Fortran files at present. \n");
                       }
                  }
             }
            else
             {
               printf ("Warning, token evaluation only valid for source files. \n");
             }
        }

  // Output statistics about how ROSE was used...
     if (project->get_verbose() > 1)
        {
          std::cout << AstNodeStatistics::traversalStatistics(project);
          std::cout << AstNodeStatistics::IRnodeUsageStatistics();
        }

  // Just set the project, the report will be generated upon calling the destructor for "timer"
  // Use option "-rose:verbose 2" to see the report.
     timer.set_project(project);

  // Skip calling the typical backend for ROSE (not required for just testing analysis)
  // This backend calls the backend compiler using the original input source file list.
     return backendCompilesUsingOriginalInputFile(project);
   }
Exemplo n.º 8
0
/*
 *  The function
 *      findScope()
 *  takes as a parameter a SgNode* which is a SgStatement*. It returns a SgNodePtrVector of all
 *  preceding scopes the SgStatement is in.
 *
 */
SgNodePtrVector
findScopes (SgNode * astNode)
{
  ROSE_ASSERT (isSgStatement (astNode));

  SgNodePtrVector returnVector;
  SgScopeStatement *currentScope;

  if (isSgScopeStatement (astNode))
    {
      currentScope = isSgScopeStatement (astNode);
      ROSE_ASSERT (currentScope != NULL);
      returnVector.push_back (astNode);
    }
  else
    {
      SgStatement *sageStatement = isSgStatement (astNode);
      ROSE_ASSERT (sageStatement != NULL);
      currentScope = sageStatement->get_scope ();
      ROSE_ASSERT (currentScope != NULL);
      returnVector.push_back (currentScope);
    }

  while (currentScope->variantT () != V_SgGlobal)
    {
      currentScope = currentScope->get_scope ();
      ROSE_ASSERT (currentScope != NULL);
      returnVector.push_back (currentScope);
    }

  //Must also include the Global Scopes of the other files in the project
  if (currentScope->variantT () == V_SgGlobal)
    {
      SgFile *sageFile = isSgFile ((currentScope)->get_parent ());
      ROSE_ASSERT (sageFile != NULL);
      SgProject *sageProject = isSgProject (sageFile->get_parent ());
      ROSE_ASSERT (sageProject != NULL);

      //Get a list of all files in the current project
      const SgFilePtrList& sageFilePtrList = sageProject->get_fileList ();

      //Iterate over the list of files to find all Global Scopes
      SgNodePtrVector globalScopes;
      for (unsigned int i = 0; i < sageFilePtrList.size (); i += 1)
	{
	  const SgSourceFile *sageFile = isSgSourceFile (sageFilePtrList[i]);
	  ROSE_ASSERT (sageFile != NULL);
	  SgGlobal *sageGlobal = sageFile->get_globalScope();
	  ROSE_ASSERT (sageGlobal != NULL);

	  returnVector.push_back (sageGlobal);
	}
    }


  return returnVector;
};
Exemplo n.º 9
0
int main( int argc, char * argv[] )
{
  vector<string> argvList(argv, argv + argc);
  SgProject* project = frontend(argvList);
  if (project->get_fileList().size() ==0)
    return 0;
  // Prepare the Def-Use Analysis
  DFAnalysis* defuse = new DefUseAnalysis(project);
  bool debug = false;
  defuse->run(debug);
  if (debug)
    defuse->dfaToDOT();

  // Prepare liveness analysis
  LivenessAnalysis* liv = new LivenessAnalysis(debug,(DefUseAnalysis*)defuse);
  ROSE_ASSERT (liv != NULL);

  // Find all function definitions
  Rose_STL_Container<SgNode*> nodeList= NodeQuery::querySubTree(project, V_SgFunctionDefinition);
  std::vector <FilteredCFGNode < IsDFAFilter > > dfaFunctions;
  Rose_STL_Container<SgNode*>::const_iterator i = nodeList.begin();
  bool abortme=false;
  for (; i!=nodeList.end();++i)
  {
    SgFunctionDefinition* func = isSgFunctionDefinition(*i);
    // run liveness analysis
    FilteredCFGNode <IsDFAFilter> rem_source = liv->run(func,abortme);
    if (abortme) {
      cerr<<"Error: Liveness analysis is ABORTING ." << endl;
      ROSE_ASSERT(false);
    }
    if (rem_source.getNode()!=NULL)
      dfaFunctions.push_back(rem_source);
  }

  SgFilePtrList file_list = project->get_fileList();
  std::string firstFileName = StringUtility::stripPathFromFileName(file_list[0]->getFileName());
  std::string fileName = firstFileName+"_liveness.dot" ;
  std::ofstream fs(fileName.c_str());
  dfaToDot(fs, string("var"), dfaFunctions, (DefUseAnalysis*)defuse, liv);
  fs.close();
  return 0;
}
Exemplo n.º 10
0
int
main ( int argc,  char * argv[] )
   {

     if (argc <= 1) {
         PrintUsage(argv[0]);
         return -1;
     }

     SgProject sageProject ( (int)argc,argv);

     SageInterface::changeAllBodiesToBlocks(&sageProject);

    CmdOptions::GetInstance()->SetOptions(argc, argv);

   int filenum = sageProject.numberOfFiles();
   for (int i = 0; i < filenum; ++i) {
      SgSourceFile* sageFile = isSgSourceFile(sageProject.get_fileList()[i]);
      ROSE_ASSERT(sageFile != NULL);

      TestCFGWrap::AnalysisDomain t = UseOA(argc, argv)? TestCFGWrap::OA : TestCFGWrap::ROSE;
      string filename = sageFile->getFileName();

#if 0 // Test harness uses stdout rather than a temporary file
      string txtname = filename.substr(filename.rfind('/')+1) + ".outx"; 
      TestCFGWrap_Text txtop(t,txtname);
#else
      TestCFGWrap_Stdout txtop(t);
#endif
      //string dotname = string(strrchr(sageFile.getFileName(),'/')+1) + ".dot";
      string dotname = filename.substr(filename.rfind('/')+1) + ".dot";
      TestCFGWrap_DOT dotop(t);
     SgGlobal *root = sageFile->get_globalScope();
     SgDeclarationStatementPtrList& declList = root->get_declarations ();
     for (SgDeclarationStatementPtrList::iterator p = declList.begin(); p != declList.end(); ++p) {
          SgFunctionDeclaration *func = isSgFunctionDeclaration(*p);
          if (func == 0)
             continue;
          SgFunctionDefinition *defn = func->get_definition();
          if (defn == 0)
             continue;
          SgNode* stmts = defn;
          if (GenerateDOT(argc, argv)) {
             dotop(stmts, dotname);
          }
          else {
             txtop(stmts);
          }
     }
   }

  return 0;
}
Exemplo n.º 11
0
int
main ( int argc,  char * argv[] )
   {

     if (argc <= 1) {
         PrintUsage(argv[0]);
         return -1;
     }

     SgProject sageProject ( (int)argc,argv);
     SageInterface::changeAllBodiesToBlocks(&sageProject);
    CmdOptions::GetInstance()->SetOptions(argc, argv);


   int filenum = sageProject.numberOfFiles();
   for (int i = 0; i < filenum; ++i) {
     SgSourceFile* sageFile = isSgSourceFile(sageProject.get_fileList()[i]);
     ROSE_ASSERT(sageFile != NULL);
     SgGlobal *root = sageFile->get_globalScope();
     SgDeclarationStatementPtrList& declList = root->get_declarations ();
     for (SgDeclarationStatementPtrList::iterator p = declList.begin(); p != declList.end(); ++p) {
          SgFunctionDeclaration *func = isSgFunctionDeclaration(*p);
          if (func == 0)
             continue;
          SgFunctionDefinition *defn = func->get_definition();
          if (defn == 0)
             continue;
          SgBasicBlock *stmts = defn->get_body();  
          AstInterfaceImpl scope(stmts);
          AstInterface fa(&scope);
          StmtVarAliasCollect alias;
          alias(fa, AstNodePtrImpl(defn));
          if (GenerateDOT(argc, argv)) {
             string name = string(strrchr(sageFile->getFileName().c_str(),'/')+1) + ".dot";
             TestDUWrap_DOT op(alias);
             op(fa, defn, name);
          }
          else {
             string name = string(strrchr(sageFile->getFileName().c_str(),'/')+1) + ".outx";
#if 0   // Test harness uses stdout now rather than a temporary file [Robb P. Matzke 2013-02-25]
             TestDUWrap_Text op(alias,name);
#else
             TestDUWrap_Stdout op(alias);
#endif
             op(fa, defn);
          }
     }
   }

  return 0;
}
Exemplo n.º 12
0
void
WalrusGraph::generateWalrusGraph( SgNode* node, string outputFilename )
   {
// Notes: The generated file in the Walrus format typically requies some editing by hand.
// For large files the "comma" always has to be remove at the end of the edge list and the node list.
// For Binary files the first edge which points to itself ("source=0 distination=0") has to be removed.
// Then the last entry for the node list has to be removed.
// Then is can often work.


     SgProject* project = isSgProject(node);
     if (project != NULL)
        {
          printf ("Found the SgProject \n");

          SgFile* fileNode = project->get_fileList()[0];
          if (isSgBinaryComposite(fileNode) != NULL)
             {
               if (project->get_binary_only() == false)
                    printf ("This should have been set already, what is wrong here! \n");

               project->set_binary_only(true);
             }

          if (project->get_binary_only() == true)
             {
               printf ("Found a binary file \n");
               WalrusGraph::isBinary = true;
             }
        }

     Counter traversal;
     traversal.traverse(node,preorder);

     printf ("node_to_index_map.size() = %zu \n",node_to_index_map.size());

     filebuf fb;
     fb.open (outputFilename.c_str(),ios::out);
     ostream os(&fb);

     ostream outputFile(&fb);
     outputFilePtr = &outputFile;
     ROSE_ASSERT(outputFilePtr != NULL);

     generateEdges(node);
     generateNodes(node);

     outputFile.flush();
   }
Exemplo n.º 13
0
/*
 * Main Function
 */
int main(int argc, char * argv[]) {
	// Build the AST used by ROSE
	SgProject* sageProject = frontend(argc, argv);

	// For each source file in the project
	SgFilePtrList & ptr_list = sageProject->get_fileList();
	for (SgFilePtrList::iterator iter = ptr_list.begin(); iter
			!= ptr_list.end(); iter++) {
		SgFile* sageFile = (*iter);
		SgSourceFile * sfile = isSgSourceFile(sageFile);
		ROSE_ASSERT(sfile);
		SgGlobal *root = sfile->get_globalScope();
		SgDeclarationStatementPtrList& declList = root->get_declarations();

		// Insert header file
		insertHeader(sfile);

		//For each function body in the scope
		for (SgDeclarationStatementPtrList::iterator p = declList.begin(); p
				!= declList.end(); ++p) {
			SgFunctionDeclaration *func = isSgFunctionDeclaration(*p);
			if (func == 0)
				continue;
			SgFunctionDefinition *defn = func->get_definition();
			if (defn == 0)
				continue;
			//ignore functions in system headers, Can keep them to test robustness
			if (defn->get_file_info()->get_filename()
					!= sageFile->get_file_info()->get_filename())
				continue;
			SgBasicBlock *body = defn->get_body();
			ROSE_ASSERT(body);

			vector<SgForStatement*> loops = querySubTree<SgForStatement> (defn,
					V_SgForStatement);
			if (loops.size() == 0)
				continue;

			visitLoops(loops);
		}

		// Generate source code from AST and call the vendor's compiler
		return backend(sageProject);
	}

}
void processTemplateHandlingOptions( SgNode* node )
   {
  // DQ (7/7/2005): Introduce tracking of performance of ROSE.
     TimingPerformance timer ("Fixup templateHandlingOptions:");

     ROSE_ASSERT(node != NULL);
     SgFile* file = TransformationSupport::getFile(node);

     if (file == NULL)
        {
       // printf ("Detected AST fragement not associated with primary AST, ignore template handling ... \n");

          SgProject *project = isSgProject(node);
          if (project != NULL)
             {
            // GB (9/4/2009): Added this case for handling SgProject nodes. We do
            // this simply by iterating over the list of files in the project and
            // calling this function recursively. This is only one level of
            // recursion since files are not nested.
               SgFilePtrList &files = project->get_fileList();
               SgFilePtrList::iterator fIterator;
               for (fIterator = files.begin(); fIterator != files.end(); ++fIterator)
                  {
                    SgFile *file = *fIterator;
                    ROSE_ASSERT(file != NULL);
                    markTemplateInstantiationsForOutput(file);
                  }
             }
        }
       else
        {
          bool buildImplicitTemplates       = (file != NULL) && (file->get_no_implicit_templates() == false);
          bool buildImplicitInlineTemplates = (file != NULL) && (file->get_no_implicit_inline_templates() == false);
#if 0
          printf ("buildImplicitTemplates       = %s \n",buildImplicitTemplates ? "true" : "false");
          printf ("buildImplicitInlineTemplates = %s \n",buildImplicitInlineTemplates ? "true" : "false");
#endif
       // This simplifies how the traversal is called!
          ProcessTemplateHandlingOptions astFixupTraversal(file,buildImplicitTemplates,buildImplicitInlineTemplates);

       // I think the default should be preorder so that the interfaces would be more uniform
          astFixupTraversal.traverse(node,preorder);
        }
   }
Exemplo n.º 15
0
Arquivo: main.C Projeto: 8l/rose
int main(int argc, char * argv[])
{

  //this adds -rose:openmp:ast_only -linearize args
  MintOptions::setInternalCommandLineArgs(argc, argv);
  
  vector<string> argvList(argv, argv + argc);

  MintOptions::GetInstance()->SetMintOptions(argvList);

  //isCFileNameSuffix ();

  //call the front end with -rose:openmp:ast_only and
  //then call the lowering explicitly

  SgProject *project = frontend (argc, argv);

  //currently we only handle single input file 
  SgSourceFile* file = isSgSourceFile(project->get_fileList()[0]);
  
  MintTools::setOutputFileName(isSgFile(file));

  //insert cuda header files. is there any? 
  MintCudaMidend::insertHeaders(project);

  //Now we have the AST and search for Mint pragmas
  MintCudaMidend::lowerMinttoCuda(file);

  if(MintOptions::GetInstance()->linearize()){
    cout << "  INFO:Mint: flattening the array accesses" << endl;  
    MintArrayInterface::linearizeArrays(file);
  }


  cout << "  INFO:Mint: calling ROSE backend" << endl;
  project->unparse();
  //return backend(project);

  cout << endl <<"  INFO:Mint: Good Job. Translation is done!" << endl << endl;

  return 0;
}
Exemplo n.º 16
0
int main(int argc, char *argv[]) {
  // Command line processing specific to SME-C:
  bool isSmecy = smecy::processCommandLine(argc, argv);
  //std::string test = CommandlineProcessing::generateStringFromArgList( CommandlineProcessing::generateArgListFromArgcArgv(argc, argv) );
  //std::cout << "command line :" << test << std::endl;

  // Call the ROSE front end, mainly the parser:
  SgProject* project = frontend(argc,argv);

  // Display the list of files to deal with:
  std::vector<SgFile*> files = project->get_fileList();
  for (SgFile * f : files)
    std::cerr << "File " << f->getFileName() << std::endl;
  //if (isSgSourceFile(files[i]))
  //OmpSupport::lower_omp(isSgSourceFile(files[i]));

  // Translating smecy #pragma if the -smecy option has been given
  std::cerr << "Translating smecy" << std::endl;
  if (isSmecy)
    smecy::translateSmecy(project);

  // There is a limitation of ROSE on the AST beautifier that cannot
  // handle more than 1 file:
  if (files.size() > 1)
    std::cerr << "PDF and DOT generation of the AST" << std::endl;
  else {
    generatePDF(*project);
    std::cerr << "Generating DOT" << std::endl;
    generateDOT(*project);
  }

  // If we want to run ROSE unit tests:
  //AstTests::runAllTests(project);

  // Finish by calling the backend: compiler, linker...
  return backend(project);
}
Exemplo n.º 17
0
int
main ( int argc,  char * argv[] )
   {

     if (argc <= 1) {
         PrintUsage(argv[0]);
         return -1;
     }

    SgProject sageProject ( argc,argv);
    SageInterface::changeAllLoopBodiesToBlocks(&sageProject);
    CmdOptions::GetInstance()->SetOptions(argc, argv);


   TestPtrAnal op;
   int filenum = sageProject.numberOfFiles();
   for (int i = 0; i < filenum; ++i) {

     SgSourceFile* sageFile = isSgSourceFile(sageProject.get_fileList()[i]);
     ROSE_ASSERT(sageFile != NULL);
     SgGlobal *root = sageFile->get_globalScope();

     AstInterfaceImpl scope(root);
     AstInterface fa(&scope);
     SgDeclarationStatementPtrList& declList = root->get_declarations ();
     for (SgDeclarationStatementPtrList::iterator p = declList.begin(); p != declList.end(); ++p) {
          SgFunctionDeclaration *func = isSgFunctionDeclaration(*p);
          if (func == 0)
             continue;
          SgFunctionDefinition *defn = func->get_definition();
          if (defn == 0)
             continue;
          op(fa, defn);
     }
   }
  return 0;
}
int
main(int argc, char** argv)
   {
     SgProject* project = frontend(argc,argv);
     ROSE_ASSERT (project != NULL);

// This is controled by using the --with-dwarf configure command line option.
#if USE_ROSE_DWARF_SUPPORT

  // The input file is the binary file...
     int binary_file_id = project->get_fileList()[0]->get_file_info()->get_file_id();

  // Increment to get the next file id (for the source file, instead of the binary file)
     int source_file_id = binary_file_id + 1;

     std::string binaryFilename = Sg_File_Info::getFilenameFromID(binary_file_id);
     printf ("file_id = %d binaryFilename = %s \n",binary_file_id,binaryFilename.c_str());

     std::string sourceFilename = Sg_File_Info::getFilenameFromID(source_file_id);
     printf ("file_id = %d sourceFilename = %s \n",source_file_id,sourceFilename.c_str());

  // Compute the source line range from the instructions in the binary executable
     std::pair<LineColumnFilePosition,LineColumnFilePosition> sourceFileRange;
     sourceFileRange = SgAsmDwarfLineList::sourceCodeRange( source_file_id );

     printf ("\nSource file line number range for:\n -- file = %s (id = %d)\n -- [(line=%d, col=%d), (line=%d, col=%d)] \n",
          sourceFilename.c_str(),source_file_id,
          sourceFileRange.first.first, sourceFileRange.first.second, 
          sourceFileRange.second.first, sourceFileRange.second.second);

  // Compute the binary executable instruction address range
     std::pair<uint64_t,uint64_t> addressRange = SgAsmDwarfLineList::instructionRange();
     printf ("\nBinary instruction address range = (0x%lx, 0x%lx) \n",addressRange.first,addressRange.second);

     int minLine = sourceFileRange.first.first;
     int maxLine = sourceFileRange.second.first;
     int columnNumber = -1;

     printf ("\nInstruction addresses computed from source positions: \n");
  // Iterate over line numbers to map back to instruction addresses
     for (int lineNumber = minLine - 2; lineNumber <= maxLine + 2; lineNumber++)
        {
       // Out of range values generate the next address or NULL.
          FileIdLineColumnFilePosition s(source_file_id,std::pair<int,int>(lineNumber,columnNumber));
          uint64_t instructionAddress = SgAsmDwarfLineList::sourceCodeToAddress(s);
          printf ("   sourceCodeToAddress(%d,%d,%d) = 0x%lx \n",s.first,s.second.first,s.second.second,instructionAddress);
        }

     uint64_t minInstructionAddress = addressRange.first;

  // Iterate over the addresses of the binary and compute the source code line numbers (limit the range so the output will be short).
     printf ("\nSource lines computed from address range (truncated to keep output short): \n");
     for (uint64_t address = minInstructionAddress - 1; address < minInstructionAddress + 25; address++)
        {
          FileIdLineColumnFilePosition s_map = SgAsmDwarfLineList::addressToSourceCode(address);
          printf ("   addressToSourceCode: address 0x%lx = (%d,%d,%d) \n",address,s_map.first,s_map.second.first,s_map.second.second);
        }
#else
     printf ("\n\nROSE must be configured with --with-dwarf=<path to libdwarf> to use Dwarf support. \n\n");
#endif

     printf ("\nProgram Terminated Normally! \n\n");

  // Skip call to backend since this is just an analysis.
     return backend(project);
   }
Exemplo n.º 19
0
int main( int argc, char *argv[] )
{
	if( argc < 2 ) {
		cout << "./amos: no input files                               " << endl;
		cout << "                                                     " << endl;
		cout << "Hi, this is Amos!                                    " << endl;
		cout << "It's my pleasure to serve you.                       " << endl;
		cout << "                                                     " << endl;
		cout << "Please type option '--help' to see guide             " << endl;
		cout << "                                                     " << endl;

		return 0;
	}

	cout << "*************************************************************" << endl;
	cout << "**                                                         **" << endl;
	cout << "**      Welcome to use OpenMP task validation system!      **" << endl;
	cout << "**                                                         **" << endl;
	cout << "**                                      editor: Amos Wang  **" << endl;
	cout << "*************************************************************\n" << endl;

	vector<string> argvList( argv, argv+argc );
	vector<string> argvList0( argv, argv+argc ); // keep original argv and argc

	command_processing( argvList );

	if( !parse_OmpTask( argvList ) ) {

		cout << "\nAmos says: I am sorry that I could not find any OpenMP task !" << endl << endl;
		return 0;
	}

	// for time counter
	long t_start;
	long t_end;
	double time_program = 0.0;

	t_start = usecs(); 
	// for time counter

	transform_Task2Loop( argvList );

	SgProject *project = frontend(argvList);
	ROSE_ASSERT( project != NULL );

#if 1
	VariantVector vv( V_SgForStatement );
	Rose_STL_Container<SgNode*> loops = NodeQuery::queryMemoryPool(vv);
	for( Rose_STL_Container<SgNode*>::iterator iter = loops.begin(); iter!= loops.end(); iter++ ) {
		SgForStatement* cur_loop = isSgForStatement(*iter);
		ROSE_ASSERT(cur_loop);
		SageInterface::normalizeForLoopInitDeclaration(cur_loop);
	}
#endif

	//initialize_analysis( project, false );
	initialize_analysis( project, false );

	//For each source file in the project
	SgFilePtrList &ptr_list = project->get_fileList();

	cout << "\n**** Amos' validation system running ****\n" << endl;

	for( SgFilePtrList::iterator iter = ptr_list.begin(); iter != ptr_list.end(); iter++ ) {

		cout << "temp source code: " << (*iter)->get_file_info()->get_filename() << endl << endl;
		SgFile *sageFile = (*iter);
		SgSourceFile *sfile = isSgSourceFile(sageFile);
		ROSE_ASSERT(sfile);
		SgGlobal *root = sfile->get_globalScope();
		SgDeclarationStatementPtrList& declList = root->get_declarations ();

		//cout << "Check point 2" << endl;
		//For each function body in the scope
		for( SgDeclarationStatementPtrList::iterator p = declList.begin(); p != declList.end(); ++p ) 
		{
			SgFunctionDeclaration *func = isSgFunctionDeclaration(*p);
			if ( func == 0 )  continue;

			SgFunctionDefinition *defn = func->get_definition();
			if ( defn == 0 )  continue;

			//ignore functions in system headers, Can keep them to test robustness
			if ( defn->get_file_info()->get_filename() != sageFile->get_file_info()->get_filename() )
				continue;

			SgBasicBlock *body = defn->get_body();

			// For each loop
			Rose_STL_Container<SgNode*> loops = NodeQuery::querySubTree( defn, V_SgForStatement ); 

			if( loops.size() == 0 ) continue;

			// X. Replace operators with their equivalent counterparts defined 
			// in "inline" annotations
			AstInterfaceImpl faImpl_1( body );
			CPPAstInterface fa_body( &faImpl_1 );
			OperatorInlineRewrite()( fa_body, AstNodePtrImpl(body) );

			// Pass annotations to arrayInterface and use them to collect 
			// alias info. function info etc.  
			ArrayAnnotation* annot = ArrayAnnotation::get_inst(); 
			ArrayInterface array_interface( *annot );
			array_interface.initialize( fa_body, AstNodePtrImpl(defn) );
			array_interface.observe( fa_body );

			// X. Loop normalization for all loops within body
			NormalizeForLoop(fa_body, AstNodePtrImpl(body));

			//cout << "Check point 3" << endl;
			for ( Rose_STL_Container<SgNode*>::iterator iter = loops.begin(); iter!= loops.end(); iter++ ) {

				SgNode* current_loop = *iter;
				SgInitializedName* invarname = getLoopInvariant( current_loop );

				if( invarname != NULL ) {

					if( invarname->get_name().getString().compare("__Amos_Wang__") == 0 ) {

						//cout << "It's __Amos_Wang__." << endl;
						//replace "for(__Amos_Wang__ = 0;__Amos_Wang__ <= 1 - 1;__Amos_Wang__ += 1)" 
						//to "#pragma omp task"
						std::string strtemp = current_loop->unparseToString();
						strtemp.replace( 0, 64, "#pragma omp task" );

						cout << "task position at: " << current_loop->get_file_info()->get_line()
							<< ", " << current_loop->get_file_info()->get_col() << endl;

						cout << "context: " << strtemp.c_str() << endl; 

						TaskValidation( current_loop );

						cout << "TaskValidation done...\n" << endl;
					}
					else continue;

				}

			}// end for loops

		}//end loop for each function body
		cout << "--------------------------------------------" << endl;

	}//end loop for each source file

	release_analysis();

	//generateDOT( *project );
	backend( project );

	//generate final file with correct directive
	amos_filter( argvList0 );

	// for time counter
	t_end = usecs();
	time_program = ((double)(t_end - t_start))/1000000;
	cout << "analysis time: " << time_program << " sec" << endl;
	//

	cout << endl << "***** Thank you for using Amos' compiler ! *****\n" << endl;

	return 0;
}
Exemplo n.º 20
0
int main(int argc, char** argv) {

  if (!containsArgument(argc, argv, "-checkAST") && 
      !containsArgument(argc, argv, "-checkGraph") &&
      !containsArgument(argc, argv, "-printTree") &&
      !containsArgument(argc, argv, "-callgraph") &&
      !containsArgument(argc, argv, "-cfa") &&
      !containsArgument(argc, argv, "-dfa") 
      ) {argc = 1;}

  if (argc < 2) {
    fprintf(stderr, "Usage: %s executableName [OPTIONS]\n", argv[0]);
    cout << "\nOPTIONS: " <<endl;
    cout << "-checkAST             - run all checkers on binary AST. " << endl; 
    cout << "-checkGraph           - run all checkers on dataflow graph. " << endl; 
    cout << "-printTree            - create dot file of AST. " << endl; 
    cout << "-callgraph            - perform callgraph analysis and print callgraph.dot file. " << endl; 
    cout << "-cfa                  - perform control flow analysis and print cfg.dot file. " << endl; 
    cout << "-dfa                  - perform dataflow flow analysis and print dfg.dot file. " << endl; 
    cout << "-inter                - perform dataflow analysis interprocedurally (default intraprocedural). " << endl; 
    cout << "-backward             - perform backward analysis (default forward). " << endl; 
    cout << "-gml                  - all graphs (except AST) are saved as gml files (default dot). " << endl; 
    cout << "-mergeedges           - aggregate edges between same nodes. " << endl; 
    cout << "-noedges              - do not print edges into dot or gml file (only nodes). " << endl; 
    return 1;
  }
  string execName = argv[1];

  lt_dlinit();
  
  // this is our test case input, we will assert on the data from this file
  test = false;
  if (execName=="buffer2.bin") {
    //cerr << "running test case on buffer2.bin !! " << endl << endl; 
    test = true;
  }
  // create out folder
  string filenameDir="out";
  mode_t mode = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
  mkdir(filenameDir.c_str(), mode);

  std::ofstream myfile;

  bool interprocedural = false;
  if (containsArgument(argc, argv, "-inter")) {
    interprocedural = true;
  }
  bool forward = true;
  if (containsArgument(argc, argv, "-backward")) {
    forward = false;
  }
  bool dot = true;
  if (containsArgument(argc, argv, "-gml")) {
    dot = false;
  }
  bool mergedEdges = false;
  if (containsArgument(argc, argv, "-mergeedges")) {
    mergedEdges = true;
  }
  bool edges = true;
  if (containsArgument(argc, argv, "-noedges")) {
    edges = false;
  }

  RoseBin_Def::RoseAssemblyLanguage = RoseBin_Def::x86;
  //fprintf(stderr, "Starting binCompass frontend...\n");
  SgProject* project = frontend(argc,argv);
  ROSE_ASSERT (project != NULL);

  SgBinaryComposite* binary = isSgBinaryComposite(project->get_fileList()[0]);
  SgAsmGenericFile* file = binary != NULL ? binary->get_binaryFile() : NULL;

  //  const SgAsmInterpretationPtrList& interps = file->get_interpretations();
  //ROSE_ASSERT (interps.size() == 1);
  //SgAsmInterpretation* interp = interps[0];
  SgAsmInterpretation* interp = SageInterface::getMainInterpretation(file);
                                
  if (containsArgument(argc, argv, "-printTree")) {
    //fprintf(stderr, "Printing AST... _binary_tree.dot\n");
    string filename="_binary_tree.dot";
    AST_BIN_Traversal* trav = new AST_BIN_Traversal();
    trav->run(interp->get_global_block(), filename);
    if (test) {
      int instrnr = trav->getNrOfInstructions();
      //cerr << " Instructions written to file: " << instrnr << endl;
      ROSE_ASSERT(instrnr==861);
    }
  }

  RoseBin_Graph* graph;

  VirtualBinCFG::AuxiliaryInformation* info = new VirtualBinCFG::AuxiliaryInformation(file);
  std::map<int,std::set<SgAsmFunction*> > components;
  GraphAlgorithms* algo = new GraphAlgorithms(info);
  // call graph analysis  *******************************************************
  if (containsArgument(argc, argv, "-callgraph")) {
    //cerr << " creating call graph ... " << endl;
    graph= new RoseBin_DotGraph();
    string callFileName = "callgraph.dot";
    if (dot==false) {
      callFileName = "callgraph.gml";
      graph= new RoseBin_GMLGraph();
    }
    RoseBin_CallGraphAnalysis* callanalysis = new RoseBin_CallGraphAnalysis(interp->get_global_block(), new RoseObj(), algo);
    callanalysis->run(graph, callFileName, !mergedEdges);
    callanalysis->getConnectedComponents(components);
    if (test) {
      //cerr << " nr of nodes visited in callanalysis : " << callanalysis->nodesVisited() << endl;
      ROSE_ASSERT(callanalysis->nodesVisited()==10);
      //cerr << " nr of edges visited in callanalysis : " << callanalysis->edgesVisited() << endl;
      ROSE_ASSERT(callanalysis->edgesVisited()==9);
    }
  }

  if (containsArgument(argc, argv, "-printTree")) {
    //fprintf(stderr, "Printing AST... _binary_tree2.dot\n");
    string filename="_binary_tree2.dot";
    AST_BIN_Traversal* trav = new AST_BIN_Traversal();
    trav->run(interp->get_global_block(), filename);
    if (test) {
      int instrnr = trav->getNrOfInstructions();
      //cerr << " Instructions written to file: " << instrnr << endl;
      ROSE_ASSERT(instrnr==861);
    }
  }

  // control flow analysis  *******************************************************
  if (containsArgument(argc, argv, "-cfa")) {
    string cfgFileName = "cfg.dot";
    graph= new RoseBin_DotGraph();
    if (dot==false) {
      cfgFileName = "cfg.gml";
      graph= new RoseBin_GMLGraph();
    }
    RoseBin_ControlFlowAnalysis* cfganalysis = new RoseBin_ControlFlowAnalysis(interp->get_global_block(), forward, new RoseObj(), edges, algo);
    cfganalysis->run(graph, cfgFileName, mergedEdges);

#if 1
    std::map<int,std::set<SgAsmFunction*> >::const_iterator comps = components.begin();
    //set<std::string> partialCFG;
    
    for (;comps!=components.end();++comps) {
      set<std::string> partialCFG;
      int nr = comps->first;
      //cerr << " found the following component " << nr << endl;
      std::set<SgAsmFunction*>  funcs = comps->second;
      std::set<SgAsmFunction*>::const_iterator it = funcs.begin();
      for (;it!=funcs.end();++it) {
	SgAsmFunction* function = *it;
	string name = function->get_name();

	name.append("_f");
	//cerr << "   binCompass CALLGRAPH ANALYSIS : found function : " << name << endl; 
	partialCFG.insert(name);
      }
      string filename = "thomas";	
      filename.append(RoseBin_support::ToString(nr));
      filename.append(".dot");
      //cerr << " binCompass writing to file " << filename << endl;
      cfganalysis->printGraph(filename,partialCFG);
    }
    //cfganalysis->printGraph(filename,partialCFG);
#endif 	
#if 0
    set<std::string> partialCFG;
    partialCFG.insert(" 80483c0_f");
    partialCFG.insert(" 8048491_f");
    partialCFG.insert(" 8048363_f");
    partialCFG.insert(" 804828f_f");
    cfganalysis->printGraph("thomas.dot",partialCFG);
#endif

    if (test) {
      //cout << " cfa -- Number of nodes == " << cfganalysis->nodesVisited() << endl;
      //cout << " cfa -- Number of edges == " << cfganalysis->edgesVisited() << endl;
      //ROSE_ASSERT(cfganalysis->nodesVisited()==210);
      //ROSE_ASSERT(cfganalysis->edgesVisited()==234);
      ROSE_ASSERT(cfganalysis->nodesVisited()==237);
      ROSE_ASSERT(cfganalysis->edgesVisited()==261);
    }
  }

  if (containsArgument(argc, argv, "-printTree")) {
    //fprintf(stderr, "Printing AST... _binary_tree3.dot\n");
    string filename="_binary_tree3.dot";
    AST_BIN_Traversal* trav = new AST_BIN_Traversal();
    trav->run(interp->get_global_block(), filename);
    if (test) {
      int instrnr = trav->getNrOfInstructions();
      //cerr << " Instructions written to file: " << instrnr << endl;
      ROSE_ASSERT(instrnr==861);
    }
  }

  if (containsArgument(argc, argv, "-dfa")) {
    //cerr << " creating dataflow graph ... " << endl;
    string dfgFileName = "dfg.dot";
    graph= new RoseBin_DotGraph();
    if (dot==false) {
      dfgFileName = "dfg.gml";
      graph= new RoseBin_GMLGraph();
    }
    RoseBin_DataFlowAnalysis* dfanalysis = new RoseBin_DataFlowAnalysis(interp->get_global_block(), forward, new RoseObj(), algo);
    dfanalysis->init(interprocedural, edges);
    dfanalysis->run(graph, dfgFileName, mergedEdges);
    if (test) {
#if 0
      cout << " dfa -- Number of nodes == " << dfanalysis->nodesVisited() << endl;
      cout << " dfa -- Number of edges == " << dfanalysis->edgesVisited() << endl;
      cout << " dfa -- Number of memWrites == " << dfanalysis->nrOfMemoryWrites() << endl;
      cout << " dfa -- Number of regWrites == " << dfanalysis->nrOfRegisterWrites() << endl;
      cout << " dfa -- Number of definitions == " << dfanalysis->nrOfDefinitions() << endl;
      cout << " dfa -- Number of uses == " << dfanalysis->nrOfUses() << endl;
#endif
      if (interprocedural) {
	ROSE_ASSERT(dfanalysis->nodesVisited()==237);
	ROSE_ASSERT(dfanalysis->edgesVisited()==284);
	ROSE_ASSERT(dfanalysis->nrOfMemoryWrites()==12);
	ROSE_ASSERT(dfanalysis->nrOfRegisterWrites()==36);
	ROSE_ASSERT(dfanalysis->nrOfDefinitions()==183);
	ROSE_ASSERT(dfanalysis->nrOfUses()==25);
      } else {
	ROSE_ASSERT(dfanalysis->nodesVisited()==237);
	ROSE_ASSERT(dfanalysis->edgesVisited()==287);
	ROSE_ASSERT(dfanalysis->nrOfMemoryWrites()==18);
	ROSE_ASSERT(dfanalysis->nrOfRegisterWrites()==77);
	ROSE_ASSERT(dfanalysis->nrOfDefinitions()==216);
	ROSE_ASSERT(dfanalysis->nrOfUses()==31);

      }
    }
  }

  if (containsArgument(argc, argv, "-checkAST") || 
      containsArgument(argc, argv, "-checkGraph")) {
    // get a list of all checkers and traverse
    vector <BC_AnalysisInterface*> checkers;
    vector <BC_GraphAnalysisInterface*> graph_checkers;

    loadAnalysisFiles(checkers);

    vector <BC_AnalysisInterface*>::const_iterator it = checkers.begin();
    for (;it!=checkers.end();it++) {
      BC_AnalysisInterface* asmf = *it;
      //cout << "\nRunning Binary Checker --- " << asmf->get_name() << endl;
      string filename = execName+"."+asmf->get_name();
      unsigned int pos = filename.find_last_of("/");
      if (filename.find_last_of("/")!=string::npos && (pos+1)<filename.length()) 
	filename = filename.substr(pos+1, filename.length());
      filename = "out/"+filename+".out";
      //cerr << "Writing file : " << filename << endl;
      myfile.open(filename.c_str());
      asmf->init(interp->get_global_block());
      asmf->traverse(interp->get_global_block(), preorder);
      asmf->finish(interp->get_global_block());
      string output = asmf->get_output();
      myfile << output << " \n";
      myfile.close();
    }  

    if (containsArgument(argc, argv, "-checkGraph")) {
      loadGraphAnalysisFiles(graph_checkers);

      //cerr << "\n ---------------- preparing to run DataFlowAnalysis (-checkGraph)" << endl;
      string dfgFileName = "dfg.dot";
      graph= new RoseBin_DotGraph();
      if (dot==false) {
	dfgFileName = "dfg.gml";
	graph= new RoseBin_GMLGraph();
      }
      RoseBin_ControlFlowAnalysis* cfganalysis = new RoseBin_ControlFlowAnalysis(interp->get_global_block(), forward, new RoseObj(), edges, algo);
      cfganalysis->run(graph, dfgFileName, mergedEdges);
      if (test) {
	//cerr << " cfa -- Number of nodes == " << cfganalysis->nodesVisited() << endl;
	//cerr << " cfa -- Number of edges == " << cfganalysis->edgesVisited() << endl;
	ROSE_ASSERT(cfganalysis->nodesVisited()==237);
	ROSE_ASSERT(cfganalysis->edgesVisited()==261);
      }

      rose_graph_integer_node_hash_map nodes = graph->get_node_index_to_node_map();
      //cerr << "CFG (-checkGraph) finished ----- Graph nr of nodes : " << nodes.size() << endl;
      ROSE_ASSERT(nodes.size()>0);

      RoseBin_DataFlowAnalysis* dfanalysis = new RoseBin_DataFlowAnalysis(interp->get_global_block(), forward, new RoseObj(), algo);
      //dfanalysis->init(interprocedural, edges,graph);
      dfanalysis->init(interprocedural, edges);
      dfanalysis->run(graph, dfgFileName, mergedEdges);

      //cerr << "DFG (-checkGraph) finished ----- Graph nr of nodes : " << nodes.size() << endl;
      vector<SgGraphNode*> rootNodes;
      dfanalysis->getRootNodes(rootNodes);

      //SgGraphNode* root1 = rootNodes[0];
      //rootNodes.clear();
      //rootNodes.push_back(root1);

      vector <BC_GraphAnalysisInterface*>::const_iterator it2 = graph_checkers.begin();
#if 0
      cerr << "\n ---------------- running graph checkers : " << graph_checkers.size() << 
	"   rootNodes size : " << rootNodes.size() << "  interprocedural : " << 
	RoseBin_support::resBool(interprocedural) << endl;
      cout << "\n ---------------- running graph checkers : " << graph_checkers.size() << 
	"   rootNodes size : " << rootNodes.size() << "  interprocedural : " << 
	RoseBin_support::resBool(interprocedural) << endl;
      cerr << "Graph : " << nodes.size() << endl;
#endif
      for (;it2!=graph_checkers.end();it2++) {
	BC_GraphAnalysisInterface* asmf = *it2;
	ROSE_ASSERT(asmf);
	//cerr << "\nRunning Binary Graph Checker --- " << asmf->get_name() << "    " <<  "  roots : " <<
	// rootNodes.size() << endl;
	// tps 04/23/08 -- fixme: this code was broken when I added the testcase -- needs to be fixed
	dfanalysis->init();
	asmf->init(graph);
	dfanalysis->traverseGraph(rootNodes, asmf, interprocedural);
      }  
    }
  }  

  unparseAsmStatementToFile("unparsed.s", interp->get_global_block());

  lt_dlexit();

  return 0;
}
Exemplo n.º 21
0
int main(int argc, char *argv[])
{
	std::string filename;

	SgProject *project = frontend(argc, argv);
	std::vector<InterproceduralInfo*> ip;
#ifdef NEWDU
	// Create the global def-use analysis
	EDefUse *defUseAnalysis=new EDefUse(project);
	if (defUseAnalysis->run(false)==0)
	{
		std::cerr<<"DFAnalysis failed!"<<endl;
	}
#endif
	string outputFileName=project->get_fileList().front()->get_sourceFileNameWithoutPath ();


	SystemDependenceGraph *sdg = new SystemDependenceGraph;
	// for all function-declarations in the AST
	NodeQuerySynthesizedAttributeType functionDeclarations = NodeQuery::querySubTree(project, V_SgFunctionDeclaration);

	for (NodeQuerySynthesizedAttributeType::iterator i = functionDeclarations.begin(); i != functionDeclarations.end(); i++)
	{
		ControlDependenceGraph *cdg;
		DataDependenceGraph *ddg;
	//	FunctionDependenceGraph * pdg;
		InterproceduralInfo *ipi;

		SgFunctionDeclaration *fDec = isSgFunctionDeclaration(*i);

		ROSE_ASSERT(fDec != NULL);

		// CI (01/08/2007): A missing function definition is an indicator to a 
		// 
		// 
		// librarycall. 
		// * An other possibility would be a programmer-mistake, which we
		// don't treat at this point.  // I assume librarycall
		if (fDec->get_definition() == NULL)
		{/*
//			if (fDec->get_file_info()->isCompilerGenerated()) continue;
			// treat librarycall -> iterprocedualInfo must be created...
			// make all call-parameters used and create a function stub for
			// the graph
			ipi=new InterproceduralInfo(fDec);
			ipi->addExitNode(fDec);
			sdg->addInterproceduralInformation(ipi);
			if (sdg->isKnownLibraryFunction(fDec))
			{
				sdg->createConnectionsForLibaryFunction(fDec);
			}
			else
			{
				sdg->createSafeConfiguration(fDec);
			}
			ip.push_back(ipi);*/

			// This is somewhat a waste of memory and a more efficient approach might generate this when needed, but at the momenent everything is created...
		}
		else
		{
			// get the control depenence for this function
			ipi=new InterproceduralInfo(fDec);

			ROSE_ASSERT(ipi != NULL);

			// get control dependence for this function defintion
			cdg = new ControlDependenceGraph(fDec->get_definition(), ipi);
                        cdg->computeAdditionalFunctioncallDepencencies();
			cdg->computeInterproceduralInformation(ipi);

			// get the data dependence for this function
			ddg = new DataDependenceGraph(fDec->get_definition(), defUseAnalysis,ipi);
			
			sdg->addFunction(cdg,ddg);
			sdg->addInterproceduralInformation(ipi);
			ip.push_back(ipi);
		}   
		// else if (fD->get_definition() == NULL)

	}
	// now all function-declarations have been process as well have all function-definitions
	filename = (outputFileName) + ".no_ii.sdg.dot";
	sdg->writeDot((char *)filename.c_str());
	
	// perform interproceduralAnalysys
	sdg->performInterproceduralAnalysis();

	filename = (outputFileName)+".deadEnds.sdg.dot";
	sdg->writeDot((char *)filename.c_str());			
	set<SgNode*> preserve;
	if (sdg->getMainFunction()!=NULL) {
	preserve.insert(sdg->getMainFunction());
	sdg->cleanUp(preserve);
	}
	filename = (outputFileName)+".final.sdg.dot";
	sdg->writeDot((char *)filename.c_str());			
}
Exemplo n.º 22
0
int
main ( int argc,  char * argv[] )
{
  //init_poet();  // initialize poet

  if (argc <= 1) {
      PrintUsage(argv[0]);
      return -1;
  }

#ifdef USE_OMEGA
  std::stringstream buffer;
  buffer << argv[argc-1] << std::endl;
  DepStats.SetFileName(buffer.str());
#endif

  vector<string> argvList(argv, argv + argc);
  CmdOptions::GetInstance()->SetOptions(argvList);

  ArrayAnnotation* array_annot = ArrayAnnotation::get_inst();
  array_annot->register_annot();

  //OperatorSideEffectAnnotation* funcAnnot=OperatorSideEffectAnnotation::get_inst();
  //funcAnnot->register_annot();
  LoopTransformInterface::set_sideEffectInfo(array_annot);

  ArrayInterface anal(*array_annot);
  LoopTransformInterface::set_arrayInfo(&anal);

  ReadAnnotation::get_inst()->read();
  if (DebugAnnot()) {
   // funcAnnot->Dump();
    array_annot->Dump();
  }

  AssumeNoAlias aliasInfo;
  LoopTransformInterface::set_aliasInfo(&aliasInfo);

  LoopTransformInterface::cmdline_configure(argvList);

  SgProject *sageProject = new SgProject ( argvList);
  FixFileInfo(sageProject);

  // DQ (11/19/2013): Added AST consistency tests.
     AstTests::runAllTests(sageProject);

  int filenum = sageProject->numberOfFiles();
  for (int i = 0; i < filenum; ++i) {

  // DQ (11/19/2013): Added AST consistency tests.
     AstTests::runAllTests(sageProject);

    SgSourceFile* sageFile = isSgSourceFile(sageProject->get_fileList()[i]);
    ROSE_ASSERT(sageFile != NULL);

    std::string fname = sageFile->get_file_info()->get_raw_filename();
    fname=fname.substr(fname.find_last_of('/')+1);

    AutoTuningInterface tuning(fname);

    LoopTransformInterface::set_tuningInterface(&tuning);
    SgGlobal *root = sageFile->get_globalScope();
    ROSE_ASSERT(root != NULL);

    SgDeclarationStatementPtrList declList = root->get_declarations ();

 // DQ (11/19/2013): Added AST consistency tests.
    AstTests::runAllTests(sageProject);

    for (SgDeclarationStatementPtrList::iterator p = declList.begin(); p != declList.end(); ++p) 
    {
      SgFunctionDeclaration *func = isSgFunctionDeclaration(*p);
      if (func == 0) continue;
      SgFunctionDefinition *defn = func->get_definition();
      if (defn == 0) continue;
      SgBasicBlock *stmts = defn->get_body();  
      AstInterfaceImpl scope(stmts);

   // DQ (11/19/2013): Added AST consistency tests.
      AstTests::runAllTests(sageProject);

   // DQ (11/19/2013): Added AST consistency tests.
      AstTests::runAllTests(sageProject);

      LoopTransformInterface::TransformTraverse(scope,AstNodePtrImpl(stmts));

#if 0
   // DQ (11/19/2013): Added AST consistency tests (this fails).
      AstTests::runAllTests(sageProject);
#endif
    }
    tuning.GenOutput();

#if 0
  // DQ (11/19/2013): Added AST consistency tests (this fails).
     AstTests::runAllTests(sageProject);
#endif
  }

//   if (CmdOptions::GetInstance()->HasOption("-fd")) {
//       simpleIndexFiniteDifferencing(sageProject);
//   }
//   if (CmdOptions::GetInstance()->HasOption("-pre")) {
//       partialRedundancyElimination(sageProject);
//   }

#if 0
  // DQ (11/19/2013): Added AST consistency tests (this fails).
     AstTests::runAllTests(sageProject);
#endif

     unparseProject(sageProject);
   //backend(sageProject);

#ifdef USE_OMEGA
     DepStats.SetDepChoice(0x1 | 0x2 | 0x4);
     DepStats.PrintResults();
#endif

  return 0;
}
Exemplo n.º 23
0
int main(int argc, char * argv[])

{
  std::string handle;
  int factor =2;
  // command line processing
  //--------------------------------------------------
  vector<std::string> argvList (argv, argv+argc);
  if (!CommandlineProcessing::isOptionWithParameter (argvList,"-rose:loopunroll:","abstract_handle",handle, true)
     || !CommandlineProcessing::isOptionWithParameter (argvList,"-rose:loopunroll:","factor",factor, true))
   {
     cout<<"Usage: loopUnrolling inputFile.c -rose:loopunroll:abstract_handle <handle_string> -rose:loopunroll:factor N"<<endl;
     return 0;
   }

  // Retrieve corresponding SgNode from abstract handle
  //--------------------------------------------------
  SgProject *project = frontend (argvList);
  SgStatement* stmt = NULL;
  ROSE_ASSERT(project != NULL);
  SgFilePtrList & filelist = project->get_fileList();
  SgFilePtrList::iterator iter= filelist.begin();
  for (;iter!=filelist.end();iter++)
  {
    SgSourceFile* sfile = isSgSourceFile(*iter);
    if (sfile != NULL)
    {     
      // prepare a file handle first
      abstract_node * file_node = buildroseNode(sfile);
      ROSE_ASSERT (file_node);
      abstract_handle* fhandle = new abstract_handle(file_node);
      ROSE_ASSERT (fhandle);
      // try to match the string and get the statement handle
      std::string cur_handle = handle;
      abstract_handle * shandle = new abstract_handle (fhandle,cur_handle);
      // it is possible that a handle is created but no matching IR node is found
      if (shandle != NULL)
      {
        if (shandle->getNode() != NULL)
        { // get SgNode from the handle
          SgNode* target_node = (SgNode*) (shandle->getNode()->getNode());
          ROSE_ASSERT(isSgStatement(target_node));
          stmt = isSgStatement(target_node);
          break; 
        }
      }
    } //end if sfile
  } // end for
  if (stmt==NULL)
  {
    cout<<"Cannot find a matching target from a handle:"<<handle<<endl;
    return 0;
  }

  // Unroll it
  //--------------------------------------------------
 if (isSgForStatement(stmt))
  {
    bool result=false;
    result = SageInterface::loopUnrolling(isSgForStatement(stmt),factor);
    ROSE_ASSERT(result != false);
  }
// Qing's loop processor does not pass postprocessing and runAllTests
//  AstPostProcessing(project);

  // generateWholeGraphOfAST("WholeAST");

  // run all tests
//  AstTests::runAllTests(project);

  // Generate source code from AST and call the vendor's compiler
  return backend(project);
}
Exemplo n.º 24
0
Arquivo: traceCPU.C Projeto: 8l/rose
int main (int argc, char *argv[])
{
   /* indicate whether include files need to be added */
   bool loopTransformApplied = false ;

   /* more bools at top of file... */
   bool withPAPI = false ;
   bool showStats = false ;
   bool enablePostProcessing = false ;

   /***********************************************/
   /* Process command line options                */
   /***********************************************/

   Rose_STL_Container<string> cmdLineArgs =
     CommandlineProcessing::generateArgListFromArgcArgv(argc,argv) ;

   if ( CommandlineProcessing::isOption(
           cmdLineArgs, "-et:", "(s|stats)", true) )
   {
     showStats = true ;
   }
   if ( CommandlineProcessing::isOption(
           cmdLineArgs, "-et:", "(p|papi)", true) )
   {
     withPAPI = true ;
   }
   if ( CommandlineProcessing::isOption(
           cmdLineArgs, "-et:", "(l|loops)", true) )
   {
     emitSeqSeg = false ;
   }
   if ( CommandlineProcessing::isOption(
           cmdLineArgs, "-et:", "noiter", true) )
   {
     countIters = false ;
   }
   if ( CommandlineProcessing::isOption(
           cmdLineArgs, "-et:", "fast", true) )
   {
     fullLoopStat = false ;
     emitSeqSeg   = false ;
     countIters   = false ;
     withPAPI     = false ;
     enablePostProcessing = true ;
   }

   dumpFunc = (showStats ? "ET_LogStats" : "ET_Dump") ;

   /***********************************************/
   /*               Invoke ROSE                   */
   /***********************************************/

   /* build AST */
   SgProject* project = frontend(argc, argv);
   ROSE_ASSERT(project);

   if (project->get_fileList().empty() == false) {

     /* make sure AST is well formed */
     AstTests::runAllTests(project);

     /* set up some needed typedefs for runtime support */

     SgGlobal *globalScope = SageInterface::getFirstGlobalScope(project) ;
     ETtype = buildTypedefDeclaration("ET_Idx_t", buildShortType(), globalScope)->get_type() ;

     /* insert probes into each function in this file */

     Rose_STL_Container<SgNode*> funcDefs =
         NodeQuery::querySubTree(project, V_SgFunctionDefinition) ;

     for (Rose_STL_Container<SgNode*>::iterator f_itr = funcDefs.begin();
                f_itr != funcDefs.end(); ++f_itr)
     {
        SgFunctionDefinition *funcDef = isSgFunctionDefinition(*f_itr) ;
        ROSE_ASSERT(funcDef);

#ifdef ET_DEBUG 
        printf("--- %s ---\n", funcDef->get_qualified_name().str()) ;
#endif

        SgBasicBlock *funcBody = funcDef->get_body() ;
        if (funcBody == NULL)
           continue ;  /* should be impossible to get here... */

        SgFunctionDeclaration *funcDecl = funcDef->get_declaration() ;
        ROSE_ASSERT(funcDecl);

        /* don't transform header file code  */
        if (strstr(funcDecl->get_name().str(), "operator"))
           continue ;

#ifdef ET_DEBUG
        printf("--- %s ---\n", funcDecl->get_name().str()) ;
#endif

        int loopCount = 0 ;  /* used to create local variable names */
        int segCount = 0 ;

        TransformFunction(funcDecl, funcBody, funcBody, &loopCount, &segCount) ;

        if (loopCount != 0)
        {
           loopTransformApplied = true ;
        }
     }

     SgFunctionDeclaration *mainFunc = SageInterface::findMain(project) ;
     if (countIters == false && (loopTransformApplied || mainFunc != NULL)) {
        SageInterface::attachArbitraryText(globalScope,
           std::string("#define ET_NO_COUNT_ITERS 1\n")) ;
     }

     /* files containing at least one loop require run-time support */

     if (loopTransformApplied)
     {
        SageInterface::attachArbitraryText(globalScope,
           std::string("#include \"ETrt.h\"\n")) ;
     }

     /* fold run-time support code into file containing main() */

     if (mainFunc != NULL)
     {

        SgFunctionDefinition *mainFuncDef = mainFunc->get_definition() ;

        /* include ETrt.c just before main() in this file */
        if (!fullLoopStat) {
          SageInterface::attachArbitraryText(globalScope,
             std::string("#define ET_SIMPLE_LOOP_STATS 1\n") );
        }
        if (enablePostProcessing) {
          SageInterface::attachArbitraryText(globalScope,
             std::string("#define ET_POST_PROCESS_SEQ_TO_LOOP 1\n") );
        }
        if (withPAPI) {
          SageInterface::attachArbitraryText(globalScope,
             std::string("#define ET_PAPI 1\n\n") );
        }
        SageInterface::attachArbitraryText(globalScope,
           std::string("#include \"ETrt.c\"\n") );

        if (withPAPI) {
           /* Insert PAPI initialization code at top of main */
           SgBasicBlock *mainBody = mainFuncDef->get_body() ;

           Rose_STL_Container<SgNode*> blockStmts =
               NodeQuery::querySubTree(mainBody, V_SgStatement,
                                       AstQueryNamespace::ChildrenOnly) ;

           for (Rose_STL_Container<SgNode*>::iterator s_itr = blockStmts.begin();
                   s_itr != blockStmts.end(); ++s_itr)
           {
              SgStatement *stmt = isSgStatement(*s_itr) ;
              ROSE_ASSERT(stmt);

              /* skip variable declarations */
              if (isSgDeclarationStatement(stmt))
                 continue ;

              SgExprStatement *initCall = buildFunctionCallStmt(
                 SgName("ET_Init"), buildVoidType(), buildExprListExp(),
                 mainFuncDef->get_body()) ;
              stmt->get_scope()->insert_statement(stmt, initCall) ;

              break ;
           }
        }

        /* insert finalization code at end of main() */
        Rose_STL_Container<SgNode*> retStmts =
            NodeQuery::querySubTree(mainFunc, V_SgReturnStmt) ;

        if (retStmts.size() > 0)
        {
           for (Rose_STL_Container<SgNode*>::iterator r_itr = retStmts.begin();
                   r_itr != retStmts.end(); ++r_itr)
           {
              SgReturnStmt *ret = isSgReturnStmt(*r_itr) ;
              ROSE_ASSERT(ret);

              SgExprStatement *sanityCall = buildFunctionCallStmt(
                 SgName("ET_SanityCheck"), buildVoidType(), buildExprListExp(),
                 mainFuncDef->get_body()) ;
              ret->get_scope()->insert_statement(ret, sanityCall) ;

              SgExprStatement *logStatCall = buildFunctionCallStmt(
                 SgName(dumpFunc), buildVoidType(), buildExprListExp(),
                 mainFuncDef->get_body()) ;
              ret->get_scope()->insert_statement(ret, logStatCall) ;
           }
        }
        else
        {
           SgExprStatement *sanityCall = buildFunctionCallStmt(
              SgName("ET_SanityCheck"), buildVoidType(), buildExprListExp(),
              mainFuncDef->get_body()) ;
           mainFuncDef->get_body()->append_statement(sanityCall) ;

           SgExprStatement *logStatCall = buildFunctionCallStmt(
              SgName(dumpFunc), buildVoidType(), buildExprListExp(),
              mainFuncDef->get_body()) ;
           mainFuncDef->get_body()->append_statement(logStatCall) ;
        }
     }
   }

   /* make sure AST is well formed */
   AstTests::runAllTests(project);

   // generateDOT (*project);

   return backend(project);
}
Exemplo n.º 25
0
int main(int argc, char** argv)
   {
  // DQ (9/1/2006): Introduce tracking of performance of ROSE at the top most level.
     TimingPerformance timer_main ("Compass performance (main): time (sec) = ",true);

     std::ios::sync_with_stdio();     // Syncs C++ and C I/O subsystems!

     if (SgProject::get_verbose() > 0)
          printf ("In compassMain.C: main() \n");

     Rose_STL_Container<std::string> commandLineArray = CommandlineProcessing::generateArgListFromArgcArgv (argc,argv);

     Compass::commandLineProcessing(commandLineArray);

  // Read the Compass parameter file (contains input data for all checkers)
  // This has been moved ahead of the parsing of the AST so that it is more 
  // obvious when it is a problem.
     Compass::Parameters params(Compass::findParameterFile());

#ifdef ROSE_MPI
     // Initialize MPI if needed...
     // need to do this to make test cases pass with MPI. 
     /* setup MPI */
     MPI_Init(&argc, &argv);
     MPI_Comm_rank(MPI_COMM_WORLD, &Compass::my_rank);
     MPI_Comm_size(MPI_COMM_WORLD, &Compass::processes);
#endif

  // Use a modified commandline that inserts specific additional options
  // to the ROSE frontend to make use with Compass more appropriate.
  // SgProject* project = frontend(argc,argv);
     SgProject* project = frontend(commandLineArray);


#ifdef HAVE_SQLITE3

     std::vector<bool> was_modified;

     //Determine if any file has been modified since the last run. If so, rerun
     //the compass checkers. The first run will always run the compass checkers.
     for (int i = 0; i < project->numberOfFiles(); ++i)
     {
       // In each file find all declarations in global scope
       SgSourceFile* sageFile = isSgSourceFile(project->get_fileList()[i]);
       std::string filename   = sageFile->getFileName();

       struct stat file_info;
       
       if ( stat(filename.c_str(), &file_info) != 0 )
         {
           std::cerr << "Error: Can not determine last modification time of file " << filename 
                     << std::endl;
       }else{

         std::string last_modified = boost::lexical_cast<std::string>(file_info.st_mtime);
         try {

           /* Read in from database here */
           sqlite3x::sqlite3_command cmd(Compass::con, "SELECT last_modified from file_last_modified where filename=\""+filename+ "\"" );

           sqlite3x::sqlite3_reader r = cmd.executereader();


           while (r.read()) {
             std::string last_modified_in_db = r.getstring(0);
             was_modified.push_back( (last_modified_in_db == last_modified) ? false : true );

           }

         } catch (std::exception& e) {std::cerr << "Exception: " << e.what() << std::endl;}

         //Update last modified time in database
         try{
           sqlite3x::sqlite3_command cmd(Compass::con,"DELETE from file_last_modified where filename=\""+filename+ "\"");
           cmd.executenonquery();
         } catch (std::exception& e) {std::cerr << "Exception: " << e.what() << std::endl;}

         try{
           sqlite3x::sqlite3_command cmd(Compass::con,"INSERT into file_last_modified(filename, last_modified) VALUES(?,?)");
           cmd.bind(1,filename);
           cmd.bind(2,last_modified);

           cmd.executenonquery();
         } catch (std::exception& e) {std::cerr << "Exception: " << e.what() << std::endl;}

                  
       };


     }

     //Continue processign iff at least one file was modified
     if( ( find(was_modified.begin(), was_modified.end(), true) != was_modified.end() )
         ||  (was_modified.size() == 0) )
     {
       //Delete violation entries that correspond to this file
       for (int i = 0; i < project->numberOfFiles(); ++i)
       {
         // In each file find all declarations in global scope
         SgSourceFile* sageFile = isSgSourceFile(project->get_fileList()[i]);
         std::string filename   = sageFile->getFileName();
         try{
           sqlite3x::sqlite3_command cmd(Compass::con,"DELETE from violations where filename=\""+filename+ "\"");
           cmd.executenonquery();
         } catch (std::exception& e) {std::cerr << "Exception: " << e.what() << std::endl;}


       }
       //continue processing
     }else
       exit(0);




#endif


#if 0
     project->display("In Compass");
#endif

     std::vector<const Compass::Checker*> traversals;

#ifdef USE_QROSE
  // This is part of incomplete GUI interface for Compass using QRose from Imperial.

  // Both of these output object work, but one is more useful for QRose.
     QRoseOutputObject* output = new QRoseOutputObject();
#endif

     Compass::PrintingOutputObject output(std::cerr);
     
        {
       // Make this in a nested scope so that we can time the buildCheckers function
          TimingPerformance timer_build ("Compass performance (build checkers and run prerequisites): time (sec) = ",false);

          buildCheckers(traversals,params,output, project);
          for ( std::vector<const Compass::Checker*>::iterator itr = traversals.begin(); itr != traversals.end(); itr++ ) {
            ROSE_ASSERT (*itr);
            Compass::runPrereqs(*itr, project);
          }
        }

     TimingPerformance timer_checkers ("Compass performance (checkers only): time (sec) = ",false);

     std::vector<std::pair<std::string, std::string> > errors;
     for ( std::vector<const Compass::Checker*>::iterator itr = traversals.begin(); itr != traversals.end(); itr++ )
        {
          if ( (*itr) != NULL )
             {
               if (Compass::verboseSetting >= 0)
                    printf ("Running checker %s \n",(*itr)->checkerName.c_str());

               try
                  {
                    int spaceAvailable = 40;
                    std::string name = (*itr)->checkerName + ":";
                    int n = spaceAvailable - name.length();
                    //Liao, 4/3/2008, bug 82, negative value
                    if (n<0) n=0;
                    std::string spaces(n,' ');
                    TimingPerformance timer (name + spaces + " time (sec) = ",false);
                    (*itr)->run(params, &output);
                  }
               catch (const std::exception& e)
                  {
                    std::cerr << "error running checker : " << (*itr)->checkerName << " - reason: " << e.what() << std::endl;
                    errors.push_back(std::make_pair((*itr)->checkerName, e.what()));
                  }
             } // if( (*itr) != NULL )
            else
             {
               std::cerr << "Error: Traversal failed to initialize" << std::endl;
               return 1;
             } // else
        } // for()

  // Support for ToolGear
     if (Compass::UseToolGear == true)
        {
          Compass::outputTgui( Compass::tguiXML, traversals, &output );
        }

#ifdef HAVE_SQLITE3
     if (Compass::UseDbOutput == true)
        {
          Compass::outputDb( Compass::outputDbName, traversals, &output );
        }
#endif

  // Output errors specific to any checkers that didn't initialize properly
     if (!errors.empty())
        {
          std::cerr << "The following checkers failed due to internal errors:" << std::endl;
          std::vector<std::pair<std::string, std::string> >::iterator e_itr;
          for (e_itr = errors.begin(); e_itr != errors.end(); ++e_itr)
             {
               std::cerr << e_itr->first << ": " << e_itr->second << std::endl;
             }
        }

  // Just set the project, the report will be generated upon calling the destructor for "timer"
     timer_main.set_project(project);

#ifdef ROSE_MPI
  MPI_Finalize();
#endif
#if 1  // Liao, 2/26/2009, add this backend support to be more friendly to build systems
       // 
     return backend(project);
#else     
     return 0;
#endif     
   }
Exemplo n.º 26
0
// DQ (5/22/2005): Added function with better name, since none of the fixes are really
// temporary any more.
void AstPostProcessing (SgNode* node)
{
    // DQ (7/7/2005): Introduce tracking of performance of ROSE.
    TimingPerformance timer ("AST post-processing:");

    // printf ("Inside of AstPostProcessing(node = %p) \n",node);

    // DQ (3/17/2007): This should be empty
    if (SgNode::get_globalMangledNameMap().size() != 0)
    {
        if (SgProject::get_verbose() > 0)
        {
            printf("AstPostProcessing(): found a node with globalMangledNameMap size not equal to 0: SgNode = %s =%s ", node->sage_class_name(),SageInterface::get_name(node).c_str());
            printf ("SgNode::get_globalMangledNameMap().size() != 0 size = %zu (clearing mangled name cache) \n",SgNode::get_globalMangledNameMap().size());
        }

        SgNode::clearGlobalMangledNameMap();
    }
    ROSE_ASSERT(SgNode::get_globalMangledNameMap().size() == 0);

    switch (node->variantT())
    {
    case V_SgProject:
    {
        SgProject* project = isSgProject(node);
        ROSE_ASSERT(project != NULL);

        // GB (8/19/2009): Added this call to perform post-processing on
        // the entire project at once. Conversely, commented out the
        // loop iterating over all files because repeated calls to
        // AstPostProcessing are slow due to repeated memory pool
        // traversals of the same nodes over and over again.
        // Only postprocess the AST if it was generated, and not were we just did the parsing.
        // postProcessingSupport(node);

        // printf ("In AstPostProcessing(): project->get_exit_after_parser() = %s \n",project->get_exit_after_parser() ? "true" : "false");
        if (project->get_exit_after_parser() == false)
        {
            postProcessingSupport (node);
        }
#if 0
        SgFilePtrList::iterator fileListIterator;
        for (fileListIterator = project->get_fileList().begin(); fileListIterator != project->get_fileList().end(); fileListIterator++)
        {
            // iterate through the list of current files
            AstPostProcessing(*fileListIterator);
        }
#endif

        // printf ("SgProject support not implemented in AstPostProcessing \n");
        // ROSE_ASSERT(false);
        break;
    }

    case V_SgDirectory:
    {
        SgDirectory* directory = isSgDirectory(node);
        ROSE_ASSERT(directory != NULL);

        printf ("SgDirectory support not implemented in AstPostProcessing \n");
        ROSE_ASSERT(false);
        break;
    }

    case V_SgFile:
    case V_SgSourceFile:
    {
        SgFile* file = isSgFile(node);
        ROSE_ASSERT(file != NULL);

        // Only postprocess the AST if it was generated, and not were we just did the parsing.
        if (file->get_exit_after_parser() == false)
        {
            postProcessingSupport (node);
        }

        break;
    }

    // Test for a binary executable, object file, etc.
    case V_SgBinaryComposite:
    {
        SgBinaryComposite* file = isSgBinaryComposite(node);
        ROSE_ASSERT(file != NULL);

        printf ("AstPostProcessing of SgBinaryFile \n");
        ROSE_ASSERT(false);

        break;
    }

    default:
    {
        // list general post-processing fixup here ...
        postProcessingSupport (node);
    }
    }

    // DQ (3/17/2007): Clear the static globalMangledNameMap, likely this is not enough and the mangled name map
    // should not be used while the names of scopes are being reset (done in the AST post-processing).
    SgNode::clearGlobalMangledNameMap();
}
Exemplo n.º 27
0
//==============================================================================
int main (int argc, char** argv)
{
  // Build the AST used by ROSE
  vector <string> argvList (argv, argv + argc);

  if (CommandlineProcessing::isOption(argvList,"-help","", false))
  {
    cout<<"---------------------Tool-Specific Help-----------------------------------"<<endl;
    cout<<"This is a source analysis to estimate FLOPS and Load/store bytes for loops in your C/C++ or Fortran code."<<endl;
    cout<<"Usage: "<<argvList[0]<<" -c ["<<report_option<<" result.txt] "<< "input.c"<<endl;
    cout<<endl;
    cout<<"The optional "<<report_option<<" option is provided for users to specify where to save the results"<<endl;
    cout<<"By default, the results will be saved into a file named report.txt"<<endl;
    cout<<"----------------------Generic Help for ROSE tools--------------------------"<<endl;
  }

  if (CommandlineProcessing::isOption(argvList,"-static-counting-only","", true))
  {
    running_mode = e_static_counting; 
  }


  if (CommandlineProcessing::isOption(argvList,"-debug","", true))
  {
    debug = true; 
  }
  else 
    debug = false;

  if (CommandlineProcessing::isOptionWithParameter (argvList, report_option,"", report_filename,true))
  {
    if (debug)
      cout<<"Using user specified file: "<<report_filename<<" for storing results."<<endl;
  }
  else
  {
    //report_filename="ai_tool_report.txt"; // this is set in src/ai_measurement.cpp already
    if (debug)
      cout<<"Using the default file:"<<report_filename<<" for storing results."<<endl;
  }

  //Save -debugdep, -annot file .. etc, 
  // used internally in ReadAnnotation and Loop transformation
  CmdOptions::GetInstance()->SetOptions(argvList);
  bool dumpAnnot = CommandlineProcessing::isOption(argvList,"","-dumpannot",true);

  //Read in annotation files after -annot 
  ArrayAnnotation* annot = ArrayAnnotation::get_inst();
  annot->register_annot();
  ReadAnnotation::get_inst()->read();
  if (dumpAnnot)
    annot->Dump();
  //Strip off custom options and their values to enable backend compiler 
  CommandlineProcessing::removeArgsWithParameters(argvList,"-annot");

  SgProject* project = frontend(argvList);

  // Insert your own manipulations of the AST here...
  SgFilePtrList file_ptr_list = project->get_fileList();
  //visitorTraversal exampleTraversal;
  for (size_t i = 0; i<file_ptr_list.size(); i++)
  {
    SgFile* cur_file = file_ptr_list[i];
    SgSourceFile* s_file = isSgSourceFile(cur_file);
    if (s_file != NULL)
    {
      // Preorder is not friendly for transformation
      //exampleTraversal.traverseWithinFile(s_file, postorder);
      Rose_STL_Container<SgNode*> nodeList = NodeQuery::querySubTree(s_file,V_SgStatement);
      if (running_mode == e_analysis_and_instrument) // reverse of pre-order for transformation mode
      {
        for (Rose_STL_Container<SgNode *>::reverse_iterator i = nodeList.rbegin(); i != nodeList.rend(); i++)
        {
          SgStatement *stmt= isSgStatement(*i);
          processStatements (stmt);
        }
      }
      else if (running_mode ==  e_static_counting) // pre-order traverse for analysis only mode 
      {
        for (Rose_STL_Container<SgNode *>::iterator i = nodeList.begin(); i != nodeList.end(); i++)
        {
          SgStatement *stmt= isSgStatement(*i);
          processStatements (stmt);
        }
      }
      else
      {
        cerr<<"Error. unrecognized execution mode:"<< running_mode<<endl;
        ROSE_ASSERT (false);
      }
    } // endif 
  } // end for

  // Generate source code from AST and invoke your
  // desired backend compiler
  return backend(project);
}
Exemplo n.º 28
0
int
main(int argc, char** argv)
   {
     ios::sync_with_stdio();                            // Syncs C++ and C I/O subsystems!
     rose::Diagnostics::initialize();                   // because librose doesn't initialize itself until frontend()

     Settings settings;
     std::vector<std::string> roseArgs = parseCommandLine(argc, argv, settings).unreachedArgs();
     roseArgs.insert(roseArgs.begin(), std::string(argv[0])); // not sure why frontend needs this, but it does.
     SgProject* project = frontend(roseArgs);
     ROSE_ASSERT (project != NULL);

  // Internal AST consistancy tests.
     AstTests::runAllTests(project);

     ROSE_ASSERT(project->numberOfFiles() == 2);

     int numberOfNodesInFile_0 = project->get_fileList()[0]->numberOfNodesInSubtree();
     int numberOfNodesInFile_1 = project->get_fileList()[1]->numberOfNodesInSubtree();

     printf ("numberOfNodesInFile_0 = %d \n",numberOfNodesInFile_0);
     printf ("numberOfNodesInFile_1 = %d \n",numberOfNodesInFile_1);

     if (settings.useOldImplementation) {
#if 0
         diff(project->get_fileList()[0],project->get_fileList()[1]);
#else

         vector< vector< SgNode* > > traversalTraceList = generateTraversalTraceList (project->get_fileList()[0],
                                                                                      project->get_fileList()[1],
                                                                                      /* minDepth = 0 */ 0,
                                                                                      /* infinite maxDepth */ -1 );
         printf ("Calling sequenceAlignment()... traversalTraceList.size() = %zu \n",traversalTraceList.size());
         sequenceAlignment  ( traversalTraceList );
         printf ("Done with call to sequenceAlignment() \n");
#endif

         // This method simply prints the edits as a side effect and doesn't return anything useful.
         Sawyer::Stopwatch tedLocalTimer;
         tree_edit_distance (project->get_fileList()[0],project->get_fileList()[1]);
         std::cout <<"local implementation of tree edit distance took " <<tedLocalTimer <<" seconds\n";
     }

     // This stuff uses the new edit distance analysis in librose
     std::cout <<"Using TreeEditDistance from librose:\n";
     EditDistance::TreeEditDistance::Analysis analysis;
     Sawyer::Stopwatch tedRoseTimer;
     analysis.compute(project->get_fileList()[0], project->get_fileList()[1],  // the subtrees to compare
                      project->get_fileList()[0], project->get_fileList()[1]); // their file restrictions
     std::cout <<"librose implementation of tree edit distance took " <<tedRoseTimer <<" seconds\n";
     EditDistance::TreeEditDistance::Edits edits = analysis.edits();
     std::cout <<"  Nodes in source tree: " <<analysis.sourceTreeNodes().size() <<"\n"
               <<"  Nodes in target tree: " <<analysis.targetTreeNodes().size() <<"\n"
               <<"  Number of edits:      " <<edits.size() <<"\n"
               <<"  Total cost of edits:  " <<analysis.cost() <<"\n"
               <<"  Relative cost:        " <<analysis.relativeCost() <<"\n"
               <<"  Individual edits:\n";
     BOOST_FOREACH (const EditDistance::TreeEditDistance::Edit &edit, edits)
         std::cout <<"    " <<edit <<"\n";
     std::ofstream graphViz("output-rose.dot");
     analysis.emitGraphViz(graphViz);
     std::cout <<"librose implementation of tree edit distance + output took " <<tedRoseTimer <<" seconds\n";
   }
Exemplo n.º 29
0
int
main ( int argc,  char * argv[] )
{
  // Initialize and check compatibility. See rose::initialize
  ROSE_INITIALIZE;

  if (argc <= 1) {
      PrintUsage(argv[0]);
      return -1;
  }
  vector<string> argvList(argv, argv + argc);
  CmdOptions::GetInstance()->SetOptions(argvList);
  AssumeNoAlias aliasInfo;
  LoopTransformInterface::cmdline_configure(argvList);
  LoopTransformInterface::set_aliasInfo(&aliasInfo);

#ifdef USE_OMEGA
  DepStats.SetFileName(buffer.str());
#endif

  OperatorSideEffectAnnotation *funcInfo = 
         OperatorSideEffectAnnotation::get_inst();
  funcInfo->register_annot();
  ReadAnnotation::get_inst()->read();
  if (DebugAnnot())
     funcInfo->Dump();
  LoopTransformInterface::set_sideEffectInfo(funcInfo);
  SgProject *project = new SgProject ( argvList);

   int filenum = project->numberOfFiles();
   for (int i = 0; i < filenum; ++i) {
  // SgFile &sageFile = sageProject->get_file(i);
  // SgGlobal *root = sageFile.get_root();
     SgSourceFile* file = isSgSourceFile(project->get_fileList()[i]);
     SgGlobal *root = file->get_globalScope();
     SgDeclarationStatementPtrList& declList = root->get_declarations ();
     for (SgDeclarationStatementPtrList::iterator p = declList.begin(); p != declList.end(); ++p) {
          SgFunctionDeclaration *func = isSgFunctionDeclaration(*p);
          if (func == 0)
             continue;
          SgFunctionDefinition *defn = func->get_definition();
          if (defn == 0)
             continue;
          SgBasicBlock *stmts = defn->get_body();  
          AstInterfaceImpl faImpl = AstInterfaceImpl(stmts);
          LoopTransformInterface::TransformTraverse(faImpl, AstNodePtrImpl(stmts));

       // JJW 10-29-2007 Adjust for iterator invalidation and possible changes to declList
          p = std::find(declList.begin(), declList.end(), func);
          assert (p != declList.end());
     }
   }

   if (CmdOptions::GetInstance()->HasOption("-fd")) {
       simpleIndexFiniteDifferencing(project);
   }

   if (CmdOptions::GetInstance()->HasOption("-pre")) {
       PRE::partialRedundancyElimination(project);
   }
#ifdef USE_OMEGA
     DepStats.SetDepChoice(0x1 | 0x2 | 0x4);
     DepStats.PrintResults();
#endif
  //Qing's loop transformations are not robust enough to pass all tests.
   //AstTests::runAllTests(sageProject);
   unparseProject(project);
   if (GenerateObj())
      return project->compileOutput();
   return 0;
}
Exemplo n.º 30
0
int main( int argc, char * argv[] )
   {
  // If we want this translator to take specific options (beyond those defined 
  // by ROSE) then insert command line processing for new options here.

  // To better support the stencil specification that might benifit from constant 
  // folding, I have turned this ON is hte frontend.  By default it is OFF so that
  // we can preserve source code as much as possible (original expression trees).
  // The Stencil DSL can be made to work in eithr setting, but this make sure that
  // dimension dependent processing of the stencil coeficients will be evaluated 
  // to constants.  I will turn this off (and thus use a less blunt axe) when the new
  // constant expression evaluation in ROSE is fixed to support more general types
  // than integer expresion (should be done by JP later today).
  // bool frontendConstantFolding = true;
     bool frontendConstantFolding = false;

  // Generate the ROSE AST.
     SgProject* project = frontend(argc,argv,frontendConstantFolding);
     ROSE_ASSERT(project != NULL);

     try
        {
          variableIdMapping.computeVariableSymbolMapping(project);
        }
     catch(char* str)
        {
          cout << "*Exception raised: " << str << endl;
        } 
     catch(const char* str) 
        {
          cout << "Exception raised: " << str << endl;
        } 
     catch(string str)
        {
          cout << "Exception raised: " << str << endl;
        }

  // variableIdMapping.toStream(cout);

#if 1
     printf ("variableIdMapping.getVariableIdSet().size() = %zu \n",variableIdMapping.getVariableIdSet().size());
     ROSE_ASSERT(variableIdMapping.getVariableIdSet().size() > 0);
#endif

#if 0
     printf ("Exiting as a test after calling variableIdMapping.computeVariableSymbolMapping(project) \n");
     ROSE_ASSERT(false);
#endif

#if 0
     printf ("Calling constant folding \n");
     ConstantFolding::constantFoldingOptimization(project,false);

#if 0
     printf ("Exiting as a test after calling ConstantFolding::constantFoldingOptimization() \n");
     ROSE_ASSERT(false);
#endif
#endif

  // DQ (2/8/2015): Find the associated SgFile so we can restrict processing to the current file.
     ROSE_ASSERT(project->get_fileList().empty() == false);
     SgFile* firstFile = project->get_fileList()[0];
     ROSE_ASSERT(firstFile != NULL);

#if DEBUG_USING_DOT_GRAPHS
  // generateDOTforMultipleFile(*project);
  // generateDOT(*project,"_before_transformation");
     AstDOTGeneration astdotgen;
     astdotgen.generateWithinFile(firstFile,DOTGeneration<SgNode*>::TOPDOWNBOTTOMUP,"_before_transformation");
#endif
#if DEBUG_USING_DOT_GRAPHS && 1
     const int MAX_NUMBER_OF_IR_NODES_TO_GRAPH_FOR_WHOLE_GRAPH = 12000;
#endif
#if DEBUG_USING_DOT_GRAPHS && 1
  // Output an optional graph of the AST (the whole graph, of bounded complexity, when active)
     generateAstGraph(project,MAX_NUMBER_OF_IR_NODES_TO_GRAPH_FOR_WHOLE_GRAPH,"_before");
#endif

  // Build the inherited attribute
     Detection_InheritedAttribute inheritedAttribute;

  // Define the traversal
     DetectionTraversal shiftCalculus_DetectionTraversal;

#if 1
     printf ("Call the Detection traversal starting at the project (root) node of the AST \n");
#endif

  // Call the traversal starting at the project (root) node of the AST
  // Detection_SynthesizedAttribute result = shiftCalculus_DetectionTraversal.traverse(project,inheritedAttribute);
     Detection_SynthesizedAttribute result = shiftCalculus_DetectionTraversal.traverseWithinFile(firstFile,inheritedAttribute);
#if 0
     printf ("Stencil Operator was transformed: %s \n",result.get_stencilOperatorTransformed() ? "true" : "false");
#endif
     ROSE_ASSERT(result.get_stencilOperatorTransformed() == false);

#if 1
     printf ("DONE: Call the Detection traversal starting at the project (root) node of the AST \n");
#endif
#if 0
     shiftCalculus_DetectionTraversal.display();
#endif
#if DEBUG_USING_DOT_GRAPHS
  // generateDOTforMultipleFile(*project);
  // generateDOT(*project,"_before_transformation");
     AstDOTGeneration astdotgen_2;
     astdotgen_2.generateWithinFile(firstFile,DOTGeneration<SgNode*>::TOPDOWNBOTTOMUP,"_after_DSL_detection");
#endif
#if 0
     printf ("Exiting after the initial traversal to detect the stencil useage. \n");
     ROSE_ASSERT(false);
#endif

  // Build the inherited attribute
     StencilEvaluation_InheritedAttribute inheritedAttribute_stencilEval;

  // Define the traversal
  // StencilEvaluationTraversal shiftCalculus_StencilEvaluationTraversal(shiftCalculus_DetectionTraversal);
     StencilEvaluationTraversal shiftCalculus_StencilEvaluationTraversal;

#if 1
     printf ("Call the StencilEvaluation traversal starting at the project (root) node of the AST \n");
#endif

  // Call the traversal starting at the project (root) node of the AST
  // StencilEvaluation_SynthesizedAttribute result_stencilEval = shiftCalculus_StencilEvaluationTraversal.traverse(project,inheritedAttribute_stencilEval);
     StencilEvaluation_SynthesizedAttribute result_stencilEval = shiftCalculus_StencilEvaluationTraversal.traverseWithinFile(firstFile,inheritedAttribute_stencilEval);

#if 0
     printf ("Stencil Evaluation was transformed: %s \n",result_stencilEval.get_stencilOperatorTransformed() ? "true" : "false");
#endif
     ROSE_ASSERT(result_stencilEval.get_stencilOperatorTransformed() == false);

#if 1
     printf ("DONE: Call the StencilEvaluation traversal starting at the project (root) node of the AST \n");
#endif
#if 1
     shiftCalculus_StencilEvaluationTraversal.displayStencil("After evaluation of stencil");
#endif
#if DEBUG_USING_DOT_GRAPHS
  // generateDOTforMultipleFile(*project);
  // generateDOT(*project,"_before_transformation");
     AstDOTGeneration astdotgen_3;
     astdotgen_3.generateWithinFile(firstFile,DOTGeneration<SgNode*>::TOPDOWNBOTTOMUP,"_after_DSL_evaluation");
#endif

#if 1
     printf ("Call generateStencilCode to generate example code \n");
#endif

#if 0
     printf ("Exiting after the second traversal to evaluate the stencils. \n");
     ROSE_ASSERT(false);
#endif

  // Generate code from stencil data structure.
     bool generateLowlevelCode = true;
     generateStencilCode(shiftCalculus_StencilEvaluationTraversal,generateLowlevelCode);

#if 1
     printf ("DONE: Call generateStencilCode to generate example code \n");
#endif

#if 0
     printf ("Exiting after call to generateStencilCode() \n");
     ROSE_ASSERT(false);
#endif

  // AST consistency tests (optional for users, but this enforces more of our tests)
     AstTests::runAllTests(project);

#if DEBUG_USING_DOT_GRAPHS
     printf ("Write out the DOT file after the transformation \n");
  // generateDOTforMultipleFile(*project,"after_transformation");
     generateDOT(*project,"_after_transformation");
     printf ("DONE: Write out the DOT file after the transformation \n");
#endif
#if DEBUG_USING_DOT_GRAPHS && 0
  // Output an optional graph of the AST (the whole graph, of bounded complexity, when active)
  // const int MAX_NUMBER_OF_IR_NODES_TO_GRAPH_FOR_WHOLE_GRAPH = 10000;
     generateAstGraph(project,MAX_NUMBER_OF_IR_NODES_TO_GRAPH_FOR_WHOLE_GRAPH,"_after");
#endif

  // Regenerate the source code but skip the call the to the vendor compiler.
     return backend(project);
   }